VOOZH about

URL: https://www.geeksforgeeks.org/go-language/function-as-a-field-in-golang-structure/

⇱ Function as a Field in Golang Structure - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Function as a Field in Golang Structure

Last Updated : 12 Jul, 2025

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
}

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


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


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


Output
Hello, C
Goodbye, C
Comment
Article Tags:

Explore