Home  >  Article  >  Backend Development  >  How to to attach a function to a struct in Golang

How to to attach a function to a struct in Golang

王林
王林Original
2024-08-06 02:58:521032browse

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
}
}

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
}

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
}

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())

}

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())

}

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...!!!!

The above is the detailed content of How to to attach a function to a struct in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn