Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Types in Go
  • Go Keywords
  • Go Control Flow
  • Go Functions
  • GoLang Structures
  • GoLang Arrays
  • GoLang Strings
  • GoLang Pointers
  • GoLang Interface
  • GoLang Concurrency
Open In App
Next Article:
Function as a Field in Golang Structure
Next article icon

Function as a Field in Golang Structure

Last Updated : 06 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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
  • Struct with Parameterized Function Field
  • Struct with Multiple Function Fields

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

Go
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

Go
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

Go
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 


Next Article
Function as a Field in Golang Structure

A

ankita_saini
Improve
Article Tags :
  • Go Language
  • Go-Functions
  • Golang

Similar Reads

    Anonymous Structure and Field in Golang
    In Golang, structures (or structs) allow us to group elements of various types into a single unit, which is useful for modeling real-world entities. Anonymous structures are unnamed, temporary structures used for a one-time purpose, while anonymous fields allow embedding fields without names.Example
    3 min read
    strings.Fields() Function in Golang With Examples
    strings.Fields() Function in Golang is used to splits the given string around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning a slice of substrings of str or an empty slice if str contains only white space. Syntax: func Fields(str string) []s
    2 min read
    reflect.Field() Function in Golang with Examples
    Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Field() Function in Golang is used to get the i'th field of the struct v. To access this function, one needs to i
    2 min read
    strings.FieldsFunc() Function in Golang With Examples
    strings.FieldsFunc() Function in Golang is used to splits the given string str at each run of Unicode code points c satisfying f(c) and returns an array of slices of str. Syntax: func FieldsFunc(str string, f func(rune) bool) []string Here, str is the given string, the rune is a built-in type meant
    2 min read
    Structure Equality in Golang
    A structure or struct in Golang is a user-defined type, which allows us to create a group of elements of different types into a single unit. Any real-world entity which has some set of properties or fields can be represented as a struct. This concept is generally compared with the classes in object-
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences