gpt4 book ai didi

go - 用作接口(interface)的复合文字的地址

转载 作者:IT王子 更新时间:2023-10-29 02:05:09 27 4
gpt4 key购买 nike

复合文字的地址在用作接口(interface)时被评估为文字本身。有人可以指出 ref spec 的部分吗?哪个处理这个?

package main
import "fmt"

type ntfc interface {
rx() int
}

type cncrt struct {
x int
}

func (c cncrt) rx() int{
return c.x
}

func rtrnsNtfca() ntfc {
return &cncrt{3}
}

func rtrnsNtfc() ntfc {
return cncrt{3}
}

func rtrnsCncrt() *cncrt {
return &cncrt{3}
}

func main() {
fmt.Println(rtrnsNtfca().rx())
fmt.Println(rtrnsNtfc().rx())
fmt.Println(rtrnsCncrt().rx())
}

还有 here .对于 future 的引用,仅链接到 Playground 而不包含此处的代码是否可以接受?

最佳答案

Spec: 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).

所以*cncrt的方法集包含了cncrt的方法集。由于rx()cncrt 方法集中的一个元素,它也会在*cncrt 的方法集中。这意味着 cncrt*cncrt 类型都实现了 ntfc 接口(interface)。

如果您有一个指针值 (*cncrt) 并且您在其上调用了 rx(),该指针将自动被解除引用,它将成为 rx() 方法。

在您的rtnsNtfca()rtnsNtfc() 函数中,ntfc 的接口(interface)值将自动创建并返回。 Go 中的接口(interface)值表示为(类型;值)对(有关更多详细信息:The Laws of Reflection #The representation of an interface)。所以 rtnsNtfca()rtnsNtfc() 都返回一个接口(interface)值,但是第一个持有类型为 *cncrt 的动态值,而后者一个包含 cncrt 类型的动态值。

而您的第三个方法 rtrnsCncrt() 返回一个具体类型 (*cncrt),那里不涉及接口(interface)包装。

注意:“反过来”

Spec: Calls:

If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

这意味着如果你声明 rx() 有一个指针接收器,并且你有一个类型为 cncrt 的变量(注意:不是指针),你可以如果它是可寻址的,仍然调用它的 rx() 方法,地址将被自动获取并用作接收者。

关于go - 用作接口(interface)的复合文字的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31790113/

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