![]() |
VOOZH | about |
In Go, you can define functions as fields within a structure (struct). This feature allows you to associate behaviors (methods) directly with data types, enabling a more organized and encapsulated way of managing data and its related operations.
package main
import "fmt"
// Define a struct with a function as a field
type Person struct {
Name string
Greet func() string
}
func main() {
person := Person{
Name: "A",
}
// Assign a function to the Greet field after person is defined
person.Greet = func() string {
return "Hello, " + person.Name
}
// Call the function field
fmt.Println(person.Greet())
}
type StructName struct {
Field1 FieldType
FunctionField func() ReturnType
}
Table of Content
You can also define a struct method that acts as a function field. This enables the struct to have behavior directly associated with it.
type StructName struct {
Field1 FieldType
MethodField func() ReturnType
}
Example
Hello, A
You can define a function field that accepts parameters, providing more flexibility in how the function operates.
type StructName struct {
Field1 FieldType
MethodField func(param1 ParamType) ReturnType
}
Example
Hi, B
You can also define multiple function fields within a single struct to encapsulate various behaviors.
type StructName struct {
Field1 FieldType
MethodField1 func() ReturnType
MethodField2 func(param1 ParamType) ReturnType
}
Example
Hello, C Goodbye, C