[英]Use of go's struct pointer as interface
I want to pass struct method as function value. 我想将struct方法作为函数值传递。 Why does compilation fail if function is required to return interface{} and it returns *struct? 如果需要函数返回interface {}并返回* struct,为什么编译会失败? It perfectly works if I try to return *struct from function that is declared to return interface{} (wrapper func). 如果我尝试从声明为返回interface {}的函数中返回* struct(包装函数),则此方法非常有用。
package main
func main() {
println("hello")
testInterface(wrapper) // works
instance := MyStruct{}
testInterface(instance.works) // works
testInterface(instance.fails) // fails: ./main.go:8: cannot use instance.fails (type func(int) *MyStruct) as type func(int) interface {} in argument to testInterface
}
func testInterface(f func() interface{}) {
f()
return
}
type MyStruct struct {
}
func (s *MyStruct) works() interface{} {
return s
}
func (s *MyStruct) fails() *MyStruct {
return s
}
func wrapper() interface{} {
s := MyStruct{}
return s.fails()
} }
That's because it does not fit the assignability criterias 那是因为它不符合可分配性标准
A value
x
is assignable to a variable of typeT
("x
is assignable toT
") in any of these cases: 在以下任何一种情况下,值x
都可以分配给类型T
的变量(“x
可以分配给T
”):
x
's type is identical toT
.x
的类型与T
相同。x
's typeV
andT
have identical underlying types and at least one ofV
orT
is not a named type.x
的类型V
和T
具有相同的基础类型,并且V
或T
中的至少一个不是命名类型。T
is an interface type andx
implementsT
.T
是接口类型,并且x
实现T
x
is a bidirectional channel value,T
is a channel type,x
's typeV
andT
have identical element types, and at least one ofV
orT
is not a named type.x
是双向通道值,T
是通道类型,x
的类型V
和T
具有相同的元素类型,并且V
或T
中的至少一个不是命名类型。x
is the predeclared identifiernil
andT
is a pointer, function, slice, map, channel, or interface type.x
是预声明的标识符nil
,T
是指针,函数,切片,映射,通道或接口类型。x
is an untyped constant representable by a value of typeT
.x
是可由类型T
的值表示的无类型常量。
So, this explains why testInterface(instance.fails)
fails: because the instance.fails
is not assignable to the f func() interface{}
. 因此,这说明了testInterface(instance.fails)
失败的原因:因为instance.fails
无法分配给f func() interface{}
。
Now the second question: 现在第二个问题:
It perfectly works if I try to return *struct from function that is declared to return interface{} (wrapper func). 如果我尝试从声明为返回interface {}的函数中返回* struct(包装函数),则此方法非常有用。
It works fine, because the value of the *struct
type is assignable to the interface{}
type because of: 它可以正常工作,因为*struct
类型的值可分配给interface{}
类型,原因是:
T
is an interface type and x
implements T
." 此可分配性规则:“ T
是接口类型, x
实现T
” References: 参考文献:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.