package main
import("fmt")type user struct{
name string
email string}// user的方法;user 又称为value recevier(不修改值)func(u user)notify(){
fmt.Println("This notify is method!")// method 当然方法也是一个函数
fmt.Println("user=", u)}// 这个不会改变内部的值 <=> changeName(u user, name string) 仅改变复制变量的值func(u user)changeName(name string){
u.name = name
}// changeEmail 又称为pointer recevier(修改值)// 这个会改变内部的值 <=> changeName(u *user, name string) 改变地址指向的值func(u *user)changeEmail(email string){
u.email = email
}// notify 是一个函数funcnotify(){// function
fmt.Println("This notify is function!")}funcmain(){notify()
tom := user{name:"tom", email:"tom@example.com"}
tom.notify()
tom.changeName("alice")
tom.notify()// 《=》 (&tom).notify() 语法糖
tom.changeEmail("tom@abc.com")
tom.notify()}
运行结果
This notify is function!
This notify is method!user={tom tom@example.com}
This notify is method!user={tom tom@example.com}
This notify is method!user={tom tom@abc.com}