gpt4 book ai didi

pointers - 关于接口(interface)分配

转载 作者:行者123 更新时间:2023-12-01 22:17:59 24 4
gpt4 key购买 nike

为什么将结构指针分配给接口(interface)时,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。这与 method sets 的方式有关。确定(强调):

A type may have a method set associated with it. The method set of an interface type is its interface. The method set of any other type T consists of all methods declared with receiver type T. The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).



The method set determines whether an interface is implemented :

An interface type specifies a method set called its interface. A variable of interface type can store a value of any type with a method set that is any superset of the interface. Such a type is said to implement the interface.



调用 *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"]
}

另见: Golang Method Sets (Pointer vs Value Receiver)

关于pointers - 关于接口(interface)分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58092804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com