方便和函数的区别:
方法能给用户定义的类型添加新的行为。方法实际上也是函数,只是在声明时,在关键字func 和方法名之间增加了一个参数。
package main import ( "fmt" ) //define a use struct type user struct { name string email string } //notyfy user recieve a method func (u user) notify() { fmt.Printf("Sending User Email to %s<%s>\n", u.name, u.email) } //changeEmail user make a method with pointer func (u *user) changeEmail(email string) { u.email = email } //main is the entry of the program func main() { bill := user{"Bill", "bill@email.com"} bill.notify() lisa := &user{"Lisa", "lisa@email.com"} lisa.notify() bill.changeEmail("bill@newdomain.com") bill.notify() lisa.changeEmail("lisa@newdomain.com") lisa.notify() }