英文:
Equivalent to class functions
问题
我在Go语言中遇到了一段代码:
type Person struct {
Id int
}
func (Person) SayHello() (string) {
return "Hello"
}
这段代码的作用类似于Go语言中的类函数吗?这个功能的确切名称是什么?我在函数接收器中找不到这个。
另外,调用部分是这样的:Person.SayHello(Person{})
。如果必须像这样传递Person{}
,那为什么不使用func (p *Person) SayHello() (string)
而是使用func (Person) SayHello() (string)
?
英文:
I came across a piece of code in Go,
type Person struct {
Id int
}
func (Person) SayHello() (string) {
return "Hello"
}
Is this equivalent to class functions in Go? what is the exact name of this? I could not find this in function receivers.
And also the calling part is like this-- Person.SayHello(Person{})
If Person{} have to be passed like this, then why use func (Person) SayHello() (string)
instead of func (p *Person) SayHello() (string)
答案1
得分: 2
我在函数接收器中找不到这个。这很奇怪,因为它是一个带有接收器的函数。
func (Person) SayHello()
- 一个带有未命名接收器类型为Person
的函数func (p Person) SayHello()
- 一个带有接收器p
类型为Person
的函数func (p *Person) SayHello()
- 一个带有接收器p
类型为指向Person
的指针的函数
值接收器和指针接收器有不同的用途,可以参考 选择值接收器还是指针接收器。
例如,Person{}.SayHello()
在使用指针接收器时无法工作。但是,如果函数需要修改接收器,那么就只能使用指针接收器。指针接收器最类似于面向对象语言中的 this
指针(但请注意,在Go语言中,将接收器命名为 this
、self
等被认为是不好的风格)。
英文:
> I could not find this in function receivers ...
That's strange, because it is a function with a receiver.
func (Person) SayHello()
- a function with an unnamed receiver of typePerson
func (p Person) SayHello()
- a function with a receiverp
of typePerson
func (p *Person) SayHello()
- a function with a receiverp
of type pointer-to-Person
Value and pointer receivers have different uses, see e.g. Choosing a value or pointer receiver.
For example, Person{}.SayHello()
won't work with a pointer receiver. But if the function needs to mutate the receiver, then there's no choice but to use a pointer receiver. Pointer receiver is most similar to the this
-pointer in object-oriented languages (but note that naming the receiver this
, self
etc. is considered bad style in Go).
答案2
得分: 1
这里只有一个带有未命名接收器参数的方法。在Go语言中,省略参数名是有效的,如果你知道不会使用该参数,这是有意义的。这在规范的这部分中有详细说明。
在这方面,接收器与其他函数参数没有区别。所以其他类似的例子包括:
func (p *Person) Do(string) {
fmt.Println("我不会按你的要求做。")
}
相关的是空白标识符,它可以用来忽略一部分函数参数:
func (p *Person) DoAndSay(_, message string) {
fmt.Println("我不会按你的要求做,但我会说出来:", message)
}
英文:
All you have here is a method with an unnamed receiver parameter. It's valid in Go to omit parameter names, and this can make sense if you know you won't be using it. This is covered in this part of the spec.
The receiver is no different than any other function parameter in this regard. So some other similar examples would include:
func (p *Person) Do(string) {
fmt.Println("I won't do what you ask.")
}
Related is the blank identifier, which can be used to ignore a subset of function parameters:
func (p *Person) DoAndSay(_, message string) {
fmt.Println("I won't do what you want, but I will say it: %s", message)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论