go语言中函数的概念和c语言中的函数类似,函数名其实是一个指针,而go语言的方法是拥有接收者的函数,其实是c++中类的方法的概念。函数是独立存在的,而方法必须有接收者,即必须依附于某个对象。go语言使用struct来抽象对象。因此方法的接收者可以是struct实例或struct的指针。
type user struct {
name string,
email string,
}
//这是函数的定义
func notify(email string) {
fmt.Println("Email is %s", email)
}
//这是方法的定义
func (u user) notify(email string) {
fmt.Println("Email is %d", email)
}
方法的接收者是struct的实例还是指针的区别是什么?实例会把struct的副本传入方法,方法内操作不影响原struct的内容。指针会把struct的地址传入方法,方法内的操作会修改到原struct的内容。