Go - struct functions fields example

In Golang, the Struct fields can be functions so in this example, we show how to define functions as fields in Struct with an example.

Go - struct functions fields example

In the example, we have the User struct. Its getUserName field is a function called getUserName.


package main

import "fmt"

type getUserName func(string, string) string

type User struct {
    firstName    string
    lastName     string
    email        string
    getUserName  getUserName
}

func main() {

    u := User{
        firstName:      "John",
        lastName: 		"Cena",
        email:        	"cena@gmail.com",
        getUserName: func(firstName string, lastName string) string {
            return fmt.Sprintf(firstName + " " + lastName)
        },
    }

    fmt.Printf(u.getUserName(u.firstName, u.lastName))
}

Output:

John Cena

Comments