Function as a Field in Golang Structure
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.
Example
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())
}
Syntax
type StructName struct {
Field1 FieldType
FunctionField func() ReturnType
}
Table of Content
Struct with Method as a Function Field
You can also define a struct method that acts as a function field. This enables the struct to have behavior directly associated with it.
Syntax
type StructName struct {
Field1 FieldType
MethodField func() ReturnType
}
Example
package main
import "fmt"
type Person struct {
Name string
Greet func() string
}
func main() {
person := Person{
Name: "A",
}
// Assign the greet function after the person is defined
person.Greet = func() string {
return "Hello, " + person.Name
}
// Call the function field
fmt.Println(person.Greet())
}
Output
Hello, A
Struct with Parameterized Function Field
You can define a function field that accepts parameters, providing more flexibility in how the function operates.
Syntax
type StructName struct {
Field1 FieldType
MethodField func(param1 ParamType) ReturnType
}
Example
package main
import "fmt"
type Person struct {
Name string
Greet func(string) string
}
func main() {
person := Person{
Name: "B",
}
// Assign the greet function after the person is defined
person.Greet = func(greeting string) string {
return greeting + ", " + person.Name
}
// Call the function field with a parameter
fmt.Println(person.Greet("Hi"))
}
Output
Hi, B
Struct with Multiple Function Fields
You can also define multiple function fields within a single struct to encapsulate various behaviors.
Syntax
type StructName struct {
Field1 FieldType
MethodField1 func() ReturnType
MethodField2 func(param1 ParamType) ReturnType
}
Example
package main
import "fmt"
type Person struct {
Name string
Greet func(string) string
Farewell func() string
}
func main() {
person := Person{
Name: "C",
}
// Assign the greet and farewell functions after the person is defined
person.Greet = func(greeting string) string {
return greeting + ", " + person.Name
}
person.Farewell = func() string {
return "Goodbye, " + person.Name
}
// Call the function fields
fmt.Println(person.Greet("Hello"))
fmt.Println(person.Farewell())
}
Output
Hello, C Goodbye, C