方便和函数的区别:

方法能给用户定义的类型添加新的行为。方法实际上也是函数,只是在声明时,在关键字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()

}

  go语言方法实例

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-04-04
  • 2022-01-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-22
  • 2022-01-09
  • 2022-12-23
  • 2021-05-05
  • 2021-11-04
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案