这是我正在查看的代码和说明的链接:https://tour.golang.org/methods/11
我将类型 *T 的方法 M 更改为 T,即从指针接收器更改为值接收器,如下所示。
package main
import (
"fmt"
"math"
)
type I interface {
M()
}
type T struct {
S string
}
func (t T) M() {
fmt.Println(t.S)
}
type F float64
func (f F) M() {
fmt.Println(f)
}
func main() {
var i I
i = &T{"Hello"}
describe(i)
i.M()
i = F(math.Pi)
describe(i)
i.M()
}
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
但是,上面的更改给了我相同的结果,因为它仍然是一个指针接收器。
(&{Hello}, *main.T)
Hello
(3.141592653589793, main.F)
3.141592653589793
我不确定这个概念是否正确。根据我的理解,因为接口(interface)变量我得到了一个指向结构 T 实例的指针,该接口(interface)变量的类型应该是一个指向结构 T 的指针,并且由于指向结构 T 的指针没有实现方法 M,它会导致 panic 。
最佳答案
The method set of the corresponding pointer type
*T
is the set of all methods declared with receiver*T
orT
(that is, it also contains the method set ofT
).[...] The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.
所以你用值接收者声明的所有方法也将属于相应指针类型的方法集,因此非指针类型实现的所有接口(interface)也将由指针类型实现(可能更多)。
关于go - 接口(interface)类型和值可以是不实现接口(interface)及其值的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55362410/