Home > OS >  Terminology and variable naming in struct member fuctions
Terminology and variable naming in struct member fuctions

Time:10-03

I'm new to Go & come from a lot of experience with OOP languages, so I'm trying to figure out the following terminology/naming:

type Foo struct {}

// The compiler says I should avoid names like `this` and `self`. Is there a precedent for what to call this variable?
// What is this type of function called? I can only think to call this an instance member of Foo
func (this *Foo) DoStuff() {}

// would this be a static member of Foo?
func (Foo) DoOtherStuff() {}

CodePudding user response:

The following is a method of *Foo. this is the receiver of the method.

func (this *Foo) DoStuff() {}

It is not the compiler complaining about the name this. You are probably using a linter software, and they all have their opinions. However, you might reconsider the naming as this is functionally equivalent to:

func DoStuff(this *Foo)

And if this fits your purpose, it is fine.

The following is also a method of Foo:

func (Foo) DoOtherStuff() {}

The only difference is that this one does not use the receiver. You still have to give it a receiver to call it. It is functionally equivalent to:

func DoOtherStuff(_ Foo) {}

There are no static members of structs in Go.

CodePudding user response:

You are asking about the naming convention for method receivers. Here's what Go's own style guide says about 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.

Contrary to the comment in the question, the compiler does not enforce this style. You are free to name the receiver this or self.

The method func (Foo) DoOtherStuff() {} is a plain method with an unnamed receiver.

Go does not have static methods. Use a function where you might have used a static method in another language.

  •  Tags:  
  • go
  • Related