Functions as Struct Fields vs. Struct Methods
In Go, functions can be embedded as fields within structs or defined as methods of those structs. Understanding the distinctions between these approaches can optimize your code design.
Fields of Function Type
Fields of function type are not true methods attached to the struct type. They store a reference to a function rather than being part of the struct's method set.
True Methods
True methods, declared with the struct type as the receiver, are integral to the struct's method set. They allow for implementing interfaces and operating on concrete types. Once defined, methods cannot be changed at runtime.
When to Use Fields of Function Type
When to Use True Methods
Example
<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>
Output:
initial changed
In this example, a function is embedded as a field in the Foo struct. By reassigning the field at runtime, we can change the behavior of the Bar method, demonstrating the flexibility of fields of function type.
The above is the detailed content of Functions as Struct Fields vs. Struct Methods: When to Use Which in Go?. For more information, please follow other related articles on the PHP Chinese website!