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…!!!!
Discover more from Coursity
Subscribe to get the latest posts sent to your email.