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

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.

主站蜘蛛池模板: 武定县| 鄂尔多斯市| 金堂县| 杭锦旗| 东莞市| 麻阳| 邢台市| 内黄县| 汕尾市| 红安县| 民权县| 三原县| 华池县| 罗城| 石泉县| 河池市| 宁都县| 高安市| 章丘市| 宜州市| 蚌埠市| 博湖县| 玉溪市| 巫溪县| 织金县| 黄陵县| 秭归县| 内丘县| 璧山县| 吴江市| 凯里市| 武功县| 锡林郭勒盟| 浦东新区| 多伦县| 武功县| 额敏县| 抚顺市| 滨州市| 罗平县| 高州市|