官术网_书友最值得收藏!

Methods

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

主站蜘蛛池模板: 丰城市| 宁南县| 康保县| 瑞丽市| 甘孜| 安丘市| 蓝山县| 景东| 江陵县| 安吉县| 罗山县| 太仆寺旗| 泸溪县| 长治县| 资阳市| 阜新| 青海省| 吴江市| 新密市| 达州市| 孙吴县| 正安县| 台江县| 淮北市| 梅河口市| 龙里县| 施秉县| 肇庆市| 光山县| 平江县| 林甸县| 海淀区| 铁岭县| 东兰县| 永寿县| 大厂| 景东| 襄垣县| 登封市| 屯门区| 浦东新区|