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

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.

主站蜘蛛池模板: 广丰县| 正蓝旗| 沁水县| 阳新县| 龙门县| 云和县| 河间市| 漾濞| 邛崃市| 克东县| 靖边县| 青田县| 肇庆市| 河曲县| 谷城县| 银川市| 河池市| 隆尧县| 邹平县| 宁夏| 安龙县| 阳春市| 新干县| 梁平县| 无极县| 漠河县| 新绛县| 孟连| 饶阳县| 哈尔滨市| 揭西县| 阿坝县| 思茅市| 绥阳县| 青河县| 格尔木市| 鹿泉市| 南丹县| 莱芜市| 聊城市| 义马市|