当前位置: > > > > 关于接口分配
关于接口分配
来源:stackoverflow
2024-04-21 21:57:35
0浏览
收藏
知识点掌握了,还需要不断练习才能熟练运用。下面米云给大家带来一个Golang开发实战,手把手教大家学习《关于接口分配》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!
问题内容
当将结构体指针分配给接口时,为什么 go 不认为这是类型不匹配错误?
package main
import "fmt"
type ABC interface {
a() string
b() int
}
type XYZ struct {
aa string
bb int
}
func (xyz XYZ) a() string {
return "XYZ"
}
func (xyz XYZ) b() int {
return 123
}
func main() {
var xyz *XYZ
var abc ABC = xyz // type of abc is *main.XYZ,I think that Golang can find this error here, but why not?
fmt.Printf("%T\n", abc)
a, ret := abc.(*XYZ)
fmt.Println(a, ret) // type of a is *main.XYZ
fmt.Println(a.a()) // will occur a error, because the type of a(*main.XYZ) not implements the interface ABC
}
我想知道为什么 go 不认为这是“var abc abc = xyz”的错误
解决方案
xyz 确实实现了 abc。这与 的确定方式有关(添加强调):
:
当调用*xyz.a()时,go编译器总是可以自动解引用指针以获得值接收者。这样做没有任何缺点,因为接收者无法修改(就调用者而言)。
当且仅当该值是可寻址时,逆运算才成立:
type T struct {}
func (*T) M()
func main() {
var t T
t.M() // ok; t is addressable and the compiler rewrites this to (*t).M()
var m map[string]T
m["x"].M() // error: cannot take the address of m["x"]
}
另请参阅:
以上就是《关于接口分配》的详细内容,更多关于的资料请关注米云公众号!
