2021-01-06 13:20:07
什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。
method的语法:
func (r Receiver) funcName (parameters) (result)
receiver可以看作是method的第一个参数,method并且支持继承和重写。
go version go1.12
/** * 什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。 * method的语法:func (r Receiver) funcName (parameters) (result)。 * receiver可以看作是method的第一个参数,method并且支持继承和重写。 */ package main import ( "fmt" ) type Human struct { name string age int } https:// 字段继承 type Student struct { Human https:// 匿名字段 school string } type Employee struct { Human https:// 匿名字段 company string } https:// 函数的另外一种形态:method,语法:func (r Receiver) funcName (parameters) (result) https:// method当作struct的字段使用 https:// receiver可以看作是method的第一个参数 https:// 指针作为receiver(接收者)和普通类型作为receiver(接收者)的区别是指针会对实例对象的内容发生操作, https:// 普通类型只是对副本进行操作 https:// method也可以继承,下面是一个匿名字段实现的method,包含这个匿名字段的struct也能调用这个method func (h *Human) Info() { https:// method里面可以访问receiver(接收者)的字段 fmt.Printf("I am %s, %d years old\n", h.name, h.age) } https:// method重写,重写匿名字段的method https:// 虽然method的名字一样,但是receiver(接收者)不一样,那么method就不一样 func (s *Student) Info() { fmt.Printf("I am %s, %d years old, I am a student at %s\n", s.name, s.age, s.school) } func (e *Employee) Info() { fmt.Printf("I am %s, %d years old, I am a employee at %s\n", e.name, e.age, e.company) } func main() { s1 := Student{Human{"Jack", 20}, "tsinghua"} e1 := Employee{Human{"Lucy", 26}, "Google"} https:// 调用method通过.访问,就像struct访问字段一样 s1.Info() e1.Info() }
以上就是详解golang中的method的详细内容,更多关于golang中的method的资料请关注其它相关文章!
原文链接:http://www.yuepc.com/a/1303.html
http://www.yuepc.com 为 “沈一博客” 唯一官方服务平台,请勿相信其他任何渠道。
2021-04-22
2021-05-20
2021-04-11
2021-05-17
2021-05-11
2021-05-15
2021-06-11
2021-06-11
2021-05-12
2021-06-13