接收器命名一致性

Receiver naming consistency

官方文档建议在所有地方使用相同的接收者名称。但是遵守那个真的有意义吗?

我的意思是,我想像 func (first Foo) concat(second Foo) (combinded Foo) 这样的东西更具表现力,而 first 只在串联的上下文中才有意义。如果我们不走那条路,我们基本上被迫求助于一些不可知但无用的接收器命名,比如 f,浪费了自我记录代码的机会。

Go Wiki: Receiver Names:

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 gives the method a special meaning. In Go, the receiver of a method is just another parameter and therefore, should be named accordingly. The name need not be as descriptive as 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.

如果你只有一个方法,它可能并不重要。如果你有一个有很多(甚至几十个方法)的类型,那么如果你在所有类型中使用相同的接收者名称会有所帮助。它更容易阅读和理解。

此外,如果你想/必须将一些代码从一种方法复制到另一种方法(重构),如果接收者名称相同,你只需复制/粘贴即可完成,你不必开始编辑不同的名称。

还有 Dave Cheney:实用 Go:编写可维护的 Go 程序的真实世界建议:

2.4. Use a consistent naming style

Another property of a good name is it should be predictable. The reader should be able to understand the use of a name when they encounter it for the first time. When they encounter a common name, they should be able to assume it has not changed meanings since the last time they saw it.

For example, if your code passes around a database handle, make sure each time the parameter appears, it has the same name. Rather than a combination of d *sql.DB, dbase *sql.DB, DB *sql.DB, and database *sql.DB, instead consolidate on something like;

db *sql.DB

Doing so promotes familiarity; if you see a db, you know it’s a *sql.DB and that it has either been declared locally or provided for you by the caller.

Similar advice applies to method receivers; use the same receiver name every method on that type. This makes it easier for the reader to internalise the use of the receiver across the methods in this type.

还有一个有趣的读物:Neither self nor this: Receivers in Go

鉴于 1. 您有一个好的方法名称, 2. 从方法声明中可以很容易地看出接收者类型,大多数情况下,像 f 这样的短名称就可以了。在您需要将接收者与参数区分开来的情况下,它建议您可以使用常规函数而不是方法,因为显然接收者没有从方法名称中遵循的明显含义。