Go

Go

Made by DeepSource

Method expression can be replaced with method call CRT-A0006

Anti-pattern
Major

It is not recommended to use method expression instead of method call.

It is simpler to use receiver functions of a type by calling them directly, rather than using selector syntax to select a function and then pass a receiver.

For foo type:

type foo struct {}

func (f foo) Bar() {
    // statements
}

func Bar(f foo) {
    // statements
}

Bad practice

f := foo{}
foo.Bar(f)

Recommended

f := foo{}
f.Bar()

This is, however, helpful when we determine programmatically which receiver function should be called, and on which receiver. For example,

type S struct {
    a int
    b int
}

func (s S) add() int {
    return s.a + s.b
}

func (s S) sub() int {
    return s.a - s.b
}

func f(i int) {
    var op func(S) int
    if i < 0 {
        op = S.add
    } else {
        op = S.sub
    }

    // do something with op
}