当前位置:网站首页>Go language - Method

Go language - Method

2022-06-21 15:38:00 Crying while learning

What is the method ?

        stay go In language , The method is a function that contains the receiver . The receiver can be a named type 、 Structure 、 The pointer .

The grammar of the method

The definition of method is almost the same as that of fir tree . Just define the receiver type before the method name .

func (t type) methodName(parameter list)(return list){
    ...
}
type Worker struct {
	name string
	age  int
}

func (w Worker) work() {
	fmt.Println(w.name, " My job is yard farmer ")
}

func main() {
	worker1 := Worker{" Zhang San ", 20}
	worker1.work()
}

Inherit

GO In the structure of language , If an anonymous field implements a method , The structure containing the anonymous field can also call this method .

The anonymous fields mentioned above are also generally structures , It can be understood as a parent class .( Anonymous field in subclass structure , Parent class )

go Language implements inheritance in object-oriented

// Person  Structure -- Parent class 
type Person struct {
	name string
	age  int
}

// Worker  Structure -- Subclass 
type Worker struct {
	workName string
	*Person  // Anonymous field , It's a structure .( A similar subclass inherits the parent class )
}

func (p Person) eat() {
	fmt.Println(p.name, " I am eating ...")
}

func main() {
	p1 := Person{" Zhang San ", 20}
	w1 := Worker{" Code the agriculture ", &p1}
	fmt.Printf("%v My occupation is :%v\n", w1.name, w1.workName)
	w1.eat()    // Inherited from parent class eat() Method 
}

 

原网站

版权声明
本文为[Crying while learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211239020000.html