神剑山庄资源网 Design By www.hcban.com
什么是method(方法)?method是函数的另外一种形态,隶属于某个类型的方法。
method的语法:
func (r Receiver) funcName (parameters) (result)
receiver可以看作是method的第一个参数,method并且支持继承和重写。
- Go中虽没有class,但依旧有method
- 通过显示说明receiver来实现与某个类型的结合
- 只能为同一个包中的类型定义方法
- receiver可以是类型的值或者指针
- 不存在方法重载
- 可以使用值或指针来调用方法,编译器会自动完成转换
- 从某种意义上来说,方法是函数的语法糖,因为receiver其实就是方法所接收的第一个参数(Method Value vs. Method Expression)
- 如果外部结构和嵌入结构存在同名方法,则优先调用外部结构的方法
- 类型别名不会拥有底层类型所附带的方法
- 方法可以调用结构中的非公开字段
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 } // 字段继承 type Student struct { Human // 匿名字段 school string } type Employee struct { Human // 匿名字段 company string } // 函数的另外一种形态:method,语法:func (r Receiver) funcName (parameters) (result) // method当作struct的字段使用 // receiver可以看作是method的第一个参数 // 指针作为receiver(接收者)和普通类型作为receiver(接收者)的区别是指针会对实例对象的内容发生操作, // 普通类型只是对副本进行操作 // method也可以继承,下面是一个匿名字段实现的method,包含这个匿名字段的struct也能调用这个method func (h *Human) Info() { // method里面可以访问receiver(接收者)的字段 fmt.Printf("I am %s, %d years old\n", h.name, h.age) } // method重写,重写匿名字段的method // 虽然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"} // 调用method通过.访问,就像struct访问字段一样 s1.Info() e1.Info() }
以上就是详解golang中的method的详细内容,更多关于golang中的method的资料请关注其它相关文章!
标签:
golang,method
神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com
暂无详解golang中的method的评论...
更新日志
2024年10月04日
2024年10月04日
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[320K/MP3][148.91MB]
- 刘雅丽.2001-丽花皇后·EMI精选王【EMI百代】【FLAC分轨】
- 齐秦.1994-黄金十年1981-1990CHINA.TOUR.LIVE精丫上华】【WAV+CUE】
- 群星.2008-本色·百代音乐人创作专辑【EMI百代】【WAV+CUE】
- 群星.2001-同步过冬AVCD【环球】【WAV+CUE】
- 群星.2020-同步过冬2020冀待晴空【环球】【WAV+CUE】
- 沈雁.1986-四季(2012梦田复刻版)【白云唱片】【WAV+CUE】
- 纪钧瀚《胎教古典音乐 钢琴与大提琴的沉浸时光》[FLAC/分轨][257.88MB]
- 《国语老歌 怀旧篇 3CD》[WAV/分轨][1.6GB]
- 班得瑞原装进口《第九张新世纪专辑:微风山谷》1CD[APE/CUE分轨][331MB]
- 陈慧琳.2008-Love.Fighters演唱会3CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 米志宏.1994-HAPPY1994【波丽佳音】【WAV+CUE】
- 潘美辰.2006-最冷的夏天(引进版)【美梦辰真】【WAV+CUE】
- 班得瑞原装进口《第十张新世纪专辑:月光水岸》1CD[APE/CUE分轨][277.2MB]
- 班得瑞原装进口《第十一张新世纪专辑:雾色山脉》1CD[APE/CUE分轨][291.6MB]