<分区>
我不太理解为什么 go 开发人员会为方法选择像 func (t Type) MethodName()
这样的语法。我无法消化这个事实,尤其是在 reading this 之后考虑到 go 是极简主义的。对于使用隐式参数访问的对象,像 func Type.MethodName()
或 func Type::MethodName()
这样的简单语法是否足够 this
或 self
。还是我错过了当前语法提供的任何优势?
<分区>
我不太理解为什么 go 开发人员会为方法选择像 func (t Type) MethodName()
这样的语法。我无法消化这个事实,尤其是在 reading this 之后考虑到 go 是极简主义的。对于使用隐式参数访问的对象,像 func Type.MethodName()
或 func Type::MethodName()
这样的简单语法是否足够 this
或 self
。还是我错过了当前语法提供的任何优势?
最佳答案
该特定语法的目标对于 Go 语言来说非常特殊,不能轻易映射到其他语言语法:
此语法允许您定义一个 method set
A type may have a method set associated with it. The method set of an interface type is its interface.
- The method set of any other type
T
consists of all methods declared with receiver typeT
.- The method set of the corresponding pointer type
*T
is the set of all methods declared with receiver*T
orT
(that is, it also contains the method set ofT
).Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set. In a method set, each method must have a unique non-blank method name.
The method set of a type determines the interfaces that the type implements and the methods that can be called using a receiver of that type.
与其说它是一种“优势”,不如说它是一种允许使用新方法轻松扩展类型的 Go 特性。
例如参见“What are some examples of Go interfaces?”。
There are two particular things that an explicit receiver declaration lets you do:
- decide that some methods will get pointer receivers and others (e.g., non-mutating methods on small structs) don't, and
- choose a context-specific name instead of '
self
' or 'this
' (e.g., you might have afunc (srv *Server)...
).
Context-specific names are considered good style in Go
The name of a method's receiver should be a reflection of its identity; often a one or two letter abbreviation of its type suffices (such as "
c
" or "cl
" for "Client
").Don't use generic names such as "
me
", "this
" or "self
", identifiers typical of object-oriented languages that place more emphasis on methods as opposed to functions.
The name need not be as descriptive as a that of a method argument, as its role is obvious and serves no documentary purpose. It can be very short as it will appear on almost every line of every method of the type; familiarity admits brevity.
Be consistent, too: if you call the receiver "c
" in one method, don't call it "cl
" in another.
关于oop - 为什么go语言的方法有奇怪的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24847582/