[英]Why does returning a concrete type not satisfy a Interface requiring a Interface return
假設我們有以下代碼
package main
type I1 interface {
Foo() string
}
type I2 interface {
Bar() I1
}
type S1 struct{}
func (s *S1) Foo() string {
return "foo"
}
type S2 struct{}
func (s *S2) Bar() *S1 {
return &S1{}
}
func main() {
x := &S2{}
var i I1 = x.Bar()
println(i.Foo())
var y I2
y = &S2{}
println(y.Bar().Foo())
}
現在,從我的觀點來看, S2
滿足I2
,因為Bar()
的返回滿足I1
,如上I1
行所示,但編譯器不同意我的觀點:
# command-line-arguments
./main.go:28:4: cannot use S2 literal (type *S2) as type I2 in assignment:
*S2 does not implement I2 (wrong type for Bar method)
have Bar() *S1
want Bar() I1
是的,我知道它們是不同的類型† ,但這不是接口接受任何滿足其要求的類型的要點嗎?
有人可以提供更多信息,說明現階段沒有考慮界面滿意度的技術原因可能是什么?
接口不滿足,因為方法簽名不匹配。 接口中指定的方法簽名為:Bar() I1 但提供的方法簽名為: Bar() *S1
您仍然可以返回指向 S1 實例的指針,但您需要匹配方法簽名。 將方法的返回類型更改為I1 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.