Functions are fields in Golang
In Golang , you can define functions as fields in a struct. This feature allows you to bind behavior (methods) directly to data types, allowing for more organized and encapsulated management of data and related operations.
For example:
package main import "fmt" // Định nghĩa một cấu trúc chưa hàm làm trương type Person struct { Name string Greet func() string } func main() { person := Person{ Name: "A", } // Gán một chức năng cho trường Chào hỏi sau khi người được xác định person.Greet = func() string { return "Hello, " + person.Name } // Gọi trường hàm fmt.Println(person.Greet()) } Syntax of function as field in Golang
type StructName struct { Field1 FieldType FunctionField func() ReturnType } Structure with methods as function fields
You can also define a struct method that acts as a function field. This allows the struct to have behavior associated directly with it.
Syntax
type StructName struct { Field1 FieldType MethodField func() ReturnType } For example:
package main import "fmt" type Person struct { Name string Greet func() string } func main() { person := Person{ Name: "A", } // Gán chức năng chào hỏi sau khi người đó được xác định person.Greet = func() string { return "Hello, " + person.Name } // Gọi trường hàm fmt.Println(person.Greet()) }
Result:
Hello, A Structure with Parameter Function Field
You can define a function field that accepts parameters, providing more flexibility in how the function behaves.
Syntax
type StructName struct { Field1 FieldType MethodField func(param1 ParamType) ReturnType } For example:
package main import "fmt" type Person struct { Name string Greet func(string) string } func main() { person := Person{ Name: "B", } // Gán hàm greet sau khi xác định được người person.Greet = func(greeting string) string { return greeting + ", " + person.Name } // Gọi trường hàm bằng 1 tham số fmt.Println(person.Greet("Hi")) } Result:
Hi, B Structure with multi-function fields
You can also define multiple function fields in a single struct to encapsulate different behaviors.
Syntax
type StructName struct { Field1 FieldType MethodField1 func() ReturnType MethodField2 func(param1 ParamType) ReturnType } For example:
package main import "fmt" type Person struct { Name string Greet func(string) string Farewell func() string } func main() { person := Person{ Name: "C", } // Gane hàm greet và farewell sau khi xác định người person.Greet = func(greeting string) string { return greeting + ", " + person.Name } person.Farewell = func() string { return "Goodbye, " + person.Name } // Gọi các trường hàm fmt.Println(person.Greet("Hello")) fmt.Println(person.Farewell()) } Result:
Hello, C Goodbye, C4 ★ | 1 Vote