gpt4 book ai didi

pointers - 接口(interface)不能调用self方法

转载 作者:数据小太阳 更新时间:2023-10-29 03:10:29 25 4
gpt4 key购买 nike

我定义了两个函数。当我向它传递一个指针时,我无法获得定义的方法。这是为什么?

type Visitor interface {
work()
}

func test(v *Visitor) {
v.work() // error
}


func test1(v Visitor) {
v.work() // ok
}

错误:

v.work undefined (type *Visitor is pointer to interface, not interface)

谁知道为什么,ths

最佳答案

func test(v *Visitor)  {
v.work() // error
}

v.work() 应该是一个方法调用。但是 v*Visitor 类型,一个指向接口(interface)的指针。 指向接口(interface)的指针有 0 个方法,它不实现任何东西(除了空接口(interface) interface{})。

当使用非指针时,值v(或者说它的类型)有一个方法work(),所以你可以调用它:

func test(v Visitor)  {
v.work() // ok
}

这里 v.work() 有效,因为 vVisitor 类型,它是一个接口(interface),它包含方法 工作()

可能令人困惑的是,如果你向一个(非指针,非接口(interface))具体类型添加方法,相应的指针类型也会有那个方法,你可以调用它。这是在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). Further rules apply to structs containing embedded fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.

不同的是,你尝试了同样的接口(interface)类型,这是行不通的。它适用于具体(非接口(interface))类型。教训是永远不要使用指向接口(interface)的指针,除非你能解释为什么需要它(很少需要)。

关于pointers - 接口(interface)不能调用self方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52774819/

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