LoginSignup
18
12

More than 5 years have passed since last update.

Goのメソッドレシーバの命名慣習

Posted at

golang-nuts MLのNaming convention for method receiver?というスレッドが興味深かったので紹介します。

メソッドレシーバの名前をself, this, meなどにするのは良くないそうです。

goのlintプログラムでも警告が出るらしいです。
https://github.com/golang/lint/blob/2d65ba4f4cbddddac5f92485e8a3e530af2888c6/lint.go#L775-L779

var badReceiverNames = map[string]bool{
    "me":   true,
    "this": true,
    "self": true,
}

https://groups.google.com/d/msg/golang-nuts/73npFHhuL9k/SmxprQ4jZJwJ
にメソッド内でNode探索する例とかではメソッドレシーバが指すものがどんどん変更されていくのでselfは不適切と説明されています。

        func (n *Node) Walk() { 
                for ; n != nil; n = n.Next() { 
                        Whatever(n.Data) 
               } 
        } 

また、下記の2つは意味的には同じとのことです。

 func (id T) name(arg U, arg2 V, ...)
 func name(id T, arg U, arg2 V, ...)

goの標準ライブラリではクラス名の頭文字をレシーバ名としていることが多いようです。
例えば bytesパッケージ だとb *Bufferとかr *Readerなどとなっています。

18
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
12