0
点赞
收藏
分享

微信扫一扫

go接口和其实现类型的指针,我认为是一样的

菜头粿子园 2022-02-26 阅读 59

A是一个接口,a是实现了接口A的类型,那么我认为A(接口)和*a(a的指针)是一个类型。

type A interface {
	out() int
}

type a struct {
	b int
}

func (x *a) out() int {
	return x.b
}

为证明二者一样,构建如下函数:

func newA() A {
	x := a{2}
	return &x //这里放到编译器没有报错,也基本说明正确了,下面在运行程序试试
}

运行程序:

func main() {
	x1 := newA()
	fmt.Println(x1.out())
}

在这里插入图片描述

举报

相关推荐

我认为的世界

0 条评论