英文:
What's the benefit of defining Go methods away from struct definitions?
问题
Go允许将方法与结构体/数据类型分开定义。这是否意味着只是在放置方法定义方面更加灵活,还是还有其他含义?
我听说过Go的结构体/方法系统被比作猴子补丁,但如果我理解正确的话,你实际上不能向任何现有类型(结构体)添加方法,因为方法必须与类型位于同一个包中。也就是说,你只能对你控制的类型进行猴子补丁。或者我有什么误解吗?
在哪些情况下,您会将类型及其方法定义在单独的源文件中(或在同一源文件的不同部分)?
英文:
Go allows one to define methods separately from the struct/datatype they work on. Does it mean just flexibility in placing the method definitions or something more?
I've heard Go's struct/methods system being compared to monkey patching, but if I understand correctly, then you really can't add methods to any existing type (struct), as methods must reside in same package as the type. Ie. you can monkey patch only the types which are under your control anyway. Or am I missing something?
In which cases would you define a type and its methods in separate source files (or in different parts of the same source file)?
答案1
得分: 10
这是Go相对于基于类型的语言的一个优势:你可以按照自己的喜好组织文件:
- 即使有很多接收器类型,你也可以将所有相似的函数放在一起
- 你可以拆分一个本来会太大的文件
像往常一样,Go没有添加一个无用的约束。所以答案也可以是“为什么不呢”?
你真的不能向任何现有类型(结构体)添加方法,因为方法必须与类型位于同一个包中
如果可以的话,在两个不同的包中使用相同的结构体上使用相同的函数名,你可能无法确定调用哪个函数。或者这将使某些包不兼容。
英文:
This is an advantage of Go over type based languages : you can organize your files as you like :
- you can put all the similar functions together, even if there are many receiver types
- you can split a file which would otherwise be too big
As frequently, Go didn't add a constraint which was useless. So the answer could also be "why not" ?
> you really can't add methods to any existing type (struct), as methods must reside in same package as the type
If you could, you might not be able to determine which function to call in case of the same function name used on the same struct in two different packages. Or that would make certain packages incompatible.
答案2
得分: 7
这可能是因为在Go语言中,你可以在任何类型上定义方法,而不仅仅是结构体:
type Age uint
func (a Age) Add(n Age) Age {
return a + n
}
这也是你可以为现有类型添加方法的方式。你需要做的是基于现有类型定义一个新类型,并按照你的需求添加方法。
英文:
This is (partly, probably) because in Go, you can have methods on any type, not just struct:
type Age uint
func (a Age) Add(n Age) Age {
return a + n
}
This is also how you can add methods to an existing type. What you do is define a new type based on that existing type, and add methods as you like.
答案3
得分: 6
猴子补丁在Go语言中是不可能的。你定义方法的类型必须与所在的包相同。
你可以在包的任何地方定义函数和方法。无论类型定义是否与类型的方法定义在同一个文件中都没有关系。
这使得可以将所有类型定义放在一个文件中,而将方法的实现放在另一个文件中。可能还有其他方法所需的辅助函数。
英文:
Monkey Patching is not possible in go. The type you define methods on must reside in the same package.
What you can do is to define functions and methods wherever you like inside the package. It doesn't really matter if the type definition is in the same file as the method definition for the type.
This makes it possible to group all type definitions in one file and have the method implementation in another. Possibly with other helper which are needed by the methods.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论