这个东东,好像其它语言很少见呢。
印象中,ruby是可以这样的。
package main
import (
"fmt"
)
type user struct {
name string
email string
}
//方法与函数的不同之处在于:函数是独立调用的,而方法寄生于变量来调用
//值接收者,主要用于不改变接收者的方法。
func (u user) notify() {
fmt.Printf("Sending User Email to %s<%s>\n",
u.name,
u.email)
}
//指针接收者,主要用于要改变接收者的方法。
func (u *user) changeEmail(email string) {
u.email = email
}
func main() {
bill := user{"Bill", "[email protected]"}
bill.notify()
lisa := &user{"Lisa", "[email protected]"}
//go编译会执行的动作:(*lisa).notify()
lisa.notify()
//go在背后会执行的动作:(&bill).changeEmail ("[email protected]")
bill.changeEmail("[email protected]")
bill.notify()
lisa.changeEmail("[email protected]")
//go编译会执行的动作:(*lisa).notify()
lisa.notify()
}