gpt4 book ai didi

go - 用指针实现接口(interface)

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

看看这段代码。一切正常:

type moninterface2 interface {
methode_commune(a,b int) int
}

type classe1 struct {
a, b int
}

type classe2 struct {
c, d int
}

func (r classe1) methode_commune(a,b int) int {
return a+b
}

func (r classe2) methode_commune(a,b int) int {
return a*b
}

func fonctiontest(param moninterface2) {
ret := param.methode_commune(2,3)
fmt.Println(ret)
}

但是如果我这样声明 methode_commune:

func (r *classe1) methode_commune(a,b int) int 
func (r *classe2) methode_commune(a,b int) int

Go 不考虑 classe1classe2 实现 moninterface2 并且代码不编译。我不明白为什么。

最佳答案

Go does not consider classe1 and classe2 implements moninterface2 and the code does not compile. I do not understand why.

因为将工作代码更改为:

func (r *classe1) methode_commune(a,b int) int 
func (r *classe2) methode_commune(a,b int) int

classe1classe2 这两种类型不再实现该接口(interface),取而代之的是*classe1* 这两种类型classe2 实现moninterface2接口(interface)。

T*T 不是同一类型。

因此,要使代码编译,您必须传递一个指向 classe1classe2moninterface2 接口(interface)是预期的。例如。 函数测试(&classe1{})

关于go - 用指针实现接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47471030/

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