Functional Fields vs. Struct Methods
In Go, there are two ways to associate a function with a struct: as a field or as a method. While both approaches serve different purposes, understanding the distinction is crucial for effective coding.
Fields of Function Type
A field of function type refers to a variable within a struct that can hold a function as its value. It provides a straightforward way to store callable routines for later execution. Unlike methods, these function fields are not part of the struct's method set.
Methods
Methods are functions explicitly attached to a specific struct type. When declared with the struct as the receiver, they become part of the struct's method set, providing access to the struct's internal state. Implementing interfaces requires defining true methods.
When to Use Which
Example
Consider the following snippet:
<code class="go">type Foo struct { Bar func() } func main() { f := Foo{ Bar: func() { fmt.Println("initial") }, } f.Bar() f.Bar = func() { fmt.Println("changed") } f.Bar() }</code>
Here, f.Bar is a field of function type. It can be reassigned at runtime, as seen when the second function value is assigned and called.
In contrast to a true method, Bar does not have access to any internal state of Foo. It operates independently from the struct itself.
The above is the detailed content of When to Use Function Fields vs. Struct Methods in Go?. For more information, please follow other related articles on the PHP Chinese website!