在类中,除了成员变量还有方法。
但是在go中没有类,所以go中的struct类似于类,它的成员方法是一种特殊的函数,和struct绑定在一起。
它的定义大致如下:
type method struct{
}
func (m method) name_method(para){
}
func (m *method) name_method(para){
}
这表示my_method()函数是绑定在mytype这个struct type上的,是与之关联的,是独属于mytype的。所以,此函数称为"方法"。所以,方法和字段一样,也是struct类型的一种属性。
定义了属于mytype的方法之后,就可以直接通过mytype来调用这个方法。
下面是一个例子:
package main
import (
"fmt"
)
type Student struct {
age int8
name string
}
func (s Student) showName() {
fmt.Println(s.name)
}
func (s *Student) setName(newName string) {
s.name = newName
}
s := Student{}
s.setName("qq")
直接调用了setName方法。 只有指针接收者才能对结构体内部的数据进行修改。
提示:
在实际 Go 语言项目开发中,struct 类型的任何一个方法使用指针接收者,通常此类型的所有方法都应该使用指针接收者,不管方法需不需要使用指针接收者。