指针和结构成员函数 [英] Pointer and Struct member function

查看:73
本文介绍了指针和结构成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我定义结构 Lock 和功能 Test 时,结构 Lock 作为函数接收者

When I define a struct Lock and a function Test with the struct Lock as the function receiver

type Lock struct {
}

func (self Lock) Test() {
    fmt.Println("Test Func")
}

我发现我可以使用 Lock 结构指针

I found that I can call this function with a Lock struct pointer

lock := &Lock{}
lock.Test()

同样,如果我将结构 Lock 和函数 Test 定义为 Lock 的指针作为接收方,则可以调用此功能通过 Lock 结构实例.

The same, if I define a struct Lock and a function Test as the Lock's pointer as the receiver, I can call this function through Lock struct instance.

那么无论接收方是结构本身还是结构指针,我都可以通过两者调用此函数吗?什么原因.据我了解,struct和struct指针完全是两种不同的类型!

So whatever the receiver is the struct itself or the struct pointer, I can call this function through the both? What's the reason. As my comprehension, the struct and the struct pointer are totally two different type!

如果这样定义接口 Locker

type Locker interface {
    Test()
}

并以结构体实例作为接收器定义结构体 Lock 和函数 Test ,我无法分配结构体指针变量到 Locker 接口var.

And define a struct Lock and a function Test with the struct instance as the receiver, I can't assign a struct pointer variable to a Locker interface var.

相反,如果定义一个结构体 Lock 和一个函数 Test 并以结构体 pointer 作为接收者,则分配一个结构体实例变量到 Locker 接口var可以正常工作!

On the contrary, If a define a struct Lock and a function Test with the struct pointer as the receiver, assign a struct instance variable to a Locker interface var can work!

我对语言设计感到很困惑.有人可以给我一些建议吗?

I'm so confused about the language design. Can anybody give me some advice?

推荐答案

通常,Go在幕后为您做事,这通常是其中一种情况.

Usually, Go does things for you under the hood and this is typically one of those cases.

当您定义一个以结构体作为接收器的函数,并向其传递指向该结构体的指针时,Go会为您进行转换:它将传递所指向的结构体的副本.

When you define a function with a struct as receiver and you pass it a pointer to the struct, then Go does the conversion for you: it passes a copy of the struct pointed to.

当您定义一个带有指针作为接收器的函数并向其传递结构时,Go会创建一个指向该结构的指针.

When you define a function with a pointer as a receiver and you pass it a struct, Go creates a pointer to this struct.

但是,在定义接口时,您正在使用类型: Locker 接口定义了一种类型,该类型实现了功能 Test().

However, when defining an interface, you're working on types: The Locker interface defines a type which implements the function Test().

对于接口,Go不会为您提供帮助:如果您的类型未实现方法,则它不会实现接口.这里没有隐藏的转换.

And with interfaces, Go won't help you: if your type doesn't implement a method, then it does not implement the interface. No hidden conversion here.

通常,最好弄清楚自己想要什么以及想要什么,从而防止Go进行这些奇怪的转换.

Usually, it's better to be clear about what you want and how you want it and thus preventing Go from doing those weird conversions.

这篇关于指针和结构成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆