Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions as the struct fields or as struct methods

Could anybody help me to clarify in which situations is better to use functions as the struct fields and when as the methods of struct?

like image 309
Thatislove Avatar asked May 15 '26 09:05

Thatislove


1 Answers

A field of function type is not a method, so it's not part of the method set of the struct type. A "true" method declared with the struct type as the receiver will be part of the method set.

That being said, if you want to implement an interface, you have no choice but to define "true" methods.

Methods are "attached" to concrete types and cannot be changed at runtime. A field of function type may be used to "mimic" virtual methods, but as said above, this is not a method. A field of function type may be reassigned at runtime.

Like in this example:

type Foo struct {
    Bar func()
}

func main() {
    f := Foo{
        Bar: func() { fmt.Println("initial") },
    }
    f.Bar()

    f.Bar = func() { fmt.Println("changed") }
    f.Bar()
}

Which outputs (try it on the Go Playground):

initial
changed

Fields of function type are often used to store callback functions. Examples from the standard lib are http.Server and http.Transport.

like image 60
icza Avatar answered May 18 '26 07:05

icza