March 2019
Beginner to intermediate
324 pages
7h 17m
English
A method is basically a function that you attach to a type. For example, let's assume we have a struct type called Person:
type Person struct{ name string age int}
Go allows us to attach a method to that type like this:
func (p Person) GetName()string{ return p.name}
The part between the func keyword and the function name, GetName(), is known as the receiver of the method.
Let's say we declare a value of type Person, like this:
var p = Person{name: "Jason",age: 29,}
Now, we can invoke the GetName method of value p, as follows:
p.GetName()
Let's create another method called GetAge(), which returns the age of the attached person. Here is the code to do so:
func (p Person) GetAge()int{ return p.age}
Now, we'll see what type embedding ...
Read now
Unlock full access