方法可以给自定义类型增加行为
package main
import "fmt"
type user struct {
name string
email string
}
func (u user) notify() {
fmt.Printf("name:%s\nEmail:%s\n",u.name, u.email)
}
// 指针可以修改值
func (u *user) set(name string, email string) {
u.name = name
u.email = email
}
func main() {
var lisa user
lisa.set("Lisa","lisa@email.com")
lisa.notify()
bill := user{"Bill", "bill@email.com"}
bill.notify()
jim := &user{"Jim", "jill@email.com"}
jim.notify()
}
运行结果:
name:Lisa
Email:lisa@email.com
name:Bill
Email:bill@email.com
name:Jim
Email:jill@email.com