方便和函数的区别:
方法能给用户定义的类型添加新的行为。方法实际上也是函数,只是在声明时,在关键字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", "[email protected]"} bill.notify() lisa := &user{"Lisa", "[email protected]"} lisa.notify() bill.changeEmail("[email protected]") bill.notify() lisa.changeEmail("[email protected]") lisa.notify() }
时间: 2024-10-13 16:18:05