1

If we have a struct of profiles, and then want to bind a method to this struct, we can do this:

 package main

import "fmt"

//定义一个装档案的结构体
type Archive struct {
    name, gender string
    age          int
    mom          *Archive
    dad          *Archive
}

//定义一个和档案结构体绑定的方法
func (person Archive) FormatArchive() {
    fmt.Printf("name: %s\n", person.name)
    fmt.Printf("gender: %s\n", person.gender)
    fmt.Printf("age: %d\n", person.age)
}

func main() {
    //    实例化一个结构体
    bill := Archive{name: "bill", age: 17, gender: "Male"}
    //    调用结构体绑定的方法
    bill.FormatArchive()
}

Then, when we want to change the data of the structure on the method of structure binding, we need to use the pointer, which is as follows:

 package main

import "fmt"

//定义一个装档案的结构体
type Archive struct {
    name, gender string
    age          int
    mom          *Archive
    dad          *Archive
}

//定义一个和档案结构体绑定的方法
func (person Archive) FormatArchive() {
    fmt.Printf("name: %s\n", person.name)
    fmt.Printf("gender: %s\n", person.gender)
    fmt.Printf("age: %d\n", person.age)
}

//定义一个改变实力参数的函数
func (person *Archive) decrease_age() {
    person.age -= 1
}

func main() {
    //    实例化一个结构体
    bill := Archive{name: "bill", age: 17, gender: "Male"}
    //    调用结构体绑定的方法
    bill.FormatArchive()
    bill.decrease_age()
    bill.FormatArchive()
}

LiberHome
409 声望1.1k 粉丝

有问题 欢迎发邮件 📩 liberhome@163.com