oop - 为什么go语言的方法有奇怪的语法

标签 oop go

<分区>

我不太理解为什么 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 type T.
  • The method set of the corresponding pointer type *T is the set of all methods declared with receiver *T or T (that is, it also contains the method set of T).

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?”。


twotwotwo添加 in the comments :

There are two particular things that an explicit receiver declaration lets you do:

  1. decide that some methods will get pointer receivers and others (e.g., non-mutating methods on small structs) don't, and
  2. choose a context-specific name instead of 'self' or 'this' (e.g., you might have a func (srv *Server)...).
    Context-specific names are considered good style in Go

参见 Wiki CodeReviewComments

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/

相关文章:

http - 将 HTTP JSON 正文响应转换为 Go 中的映射

go - 重命名项目后不允许使用内部软件包xxx

json - Golang - 使用/遍历 JSON 解析映射

c - 从模块的外部上下文中正确隐藏函数

java - 使用 super AND 实例变量的构造函数

python - Django:覆盖继承的字段选项

http - 如何获得第一个 HTTP(重定向)响应?

go - 如何在官方围棋之旅中播种随机数生成器?

c# - 构造函数中的基础对象作为向下转换的替代方法

python - 如何修改库的类以使其使用我对另一个库类的扩展?