英文:
Method prefixes in Go
问题
在Go语言中,可以在函数上使用"前缀"。这有什么用处?有哪些使用场景?
示例:
type a struct {
Thing string
}
func (something a) b() {
fmt.Println(something.Thing)
}
在这个示例中,函数b()具有接收者(something a),这是一种将函数与特定类型相关联的方式。通过将函数与类型相关联,我们可以在该类型的实例上调用该函数。在这种情况下,我们可以通过创建a类型的实例并调用b()函数来打印出Thing字段的值。这种方式可以使代码更具可读性和组织性,并且可以将相关的操作封装在类型的方法中。
英文:
In go, there's a "prefix" that you can put on a function. How is this useful? What are the use cases for this?
Example:
type a struct {
Thing string
}
func (something a) b() {
fmt.Println(something.Thing)
}
答案1
得分: 4
编程是一种交流:你向计算机传达它应该做什么,并与其他程序员(包括你未来的自己)进行交流。许多高级编程结构的目的是使代码更具表达性,即更清楚地陈述程序员的意图。
Go语言的函数接收器类似于传统面向对象语言中的“self”对象。它是一种将一组函数组合在一起并表示“这些方法主要用于操作此类型的对象”的方式,而不仅仅是通用的实用方法,恰好接受该类型的参数。换句话说,它们存在的目的是描述由结构体描述状态的抽象对象的行为。
英文:
Programming is communication: you are communicating to the machine what it should do, and communicating to other programmers (including your future self). Many higher-level programming constructs serve the purpose of making code more expressive--that is, more clearly stating the programmer's intent.
Go's function receivers are like the "self" object in more traditional object-oriented languages. It's a way of grouping a set of functions together and saying "these methods exist primarily to operate on objects of this type", rather than just being general utility methods that happen to take an argument of that type. In other words, they exist to describe the behavior of the abstract object whose state is described by the structure.
答案2
得分: 1
这意味着该函数与结构体关联在一起,在这种情况下,你可以在其他地方使用a.b()
。
英文:
It means that the function is attached to the struct, in this case, so that you can do a.b()
somewhere else.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论