DEV Community

Cover image for How to to attach a function to a struct in Golang
Chibueze  felix
Chibueze felix

Posted on

How to to attach a function to a struct in Golang

If you are coming from other languages such as php, C# , Dart etc you would be familiar with creating methods for classes. Usually these methods implement one action for that class. In such OOP languages you create such methods in the class scope such as :

class ClassName{
....
 function functionName(){
  // perform action
}
}
Enter fullscreen mode Exit fullscreen mode

In go you first create a struct then you can attach receivers to perform specific actions for the struct. For instance we have as model User to which we want it to have a method that returns the user's full name we have that as shown below:

type myUser struct{
 FirstName string
LastName string
PostalCode string
DateOfBirth time.Time
}
Enter fullscreen mode Exit fullscreen mode

Above we just created a User type with the various attributes such as FirstName, LastName .... , we want to have a method that perform some special action for the 'myUser' type in this case just return the full name form the stated attributes FirstName,LastName.

We can go n a create a receiver function fullname that returns a string.

func (user *myUser) fullname() (string, string){
   return user.FirstName ,user.LastName
}

Enter fullscreen mode Exit fullscreen mode

How can we use this? we could test this directly in the main function just to see how it works:

func main() {

    user := myUser{
        FirstName: "Felix",
        LastName:  "chi",
    }
    fmt.Println(user.fullname())

}
Enter fullscreen mode Exit fullscreen mode

Hence we have successfully created a receiver method for our myUser struct. The full ode will loke like so:

package main

import (
    "fmt"
    "time"
)

type myUser struct {
    FirstName   string
    LastName    string
    PostalCode  string
    DateOfBirth time.Time
}

func (user *myUser) fullname() (string, string) {
    return user.FirstName, user.LastName
}

func main() {

    user := myUser{
        FirstName: "Felix",
        LastName:  "chi",
    }
    fmt.Println(user.fullname())

}
Enter fullscreen mode Exit fullscreen mode

So whats next? go ahead and paste code on https://go.dev/play/ to see how it truly works. See in your on my next post...!!!!

Top comments (0)