问题背景
Go语言的面向对象在概念上与java大同小异,但是由于Go语言在给struct添加method的时候需有一个显示的接收者(receiver),receiver可以是指针类型或是struct的形参,二者到底有啥区别是在学习Go面向对象内容时最容易糊涂的地方。
问题描述
为了更好的阐述问题,首先撸上一段小代码:
//定义一个名为Controller的类
type Controller struct {
domain string
count int
}
//给Controller添加第一个成员方法firstFunc
func (c *Controller) firstFunc(domain string, count int) {
c.domain = domain
c.count = count
fmt.Println("firstFunc's domain is "+c.domain+" count is ", c.count)
}
//给Controller添加第二个成员方法secondFunc
func (c Controller) secondFunc(domain string, count int) {
c.domain = domain
c.count = count
fmt.Println("secondFunc's domain is "+c.domain+" count is ", c.count)
}
如上,在Go中定义类用struct类型,在Controller类有两个field,分别为domian和count,还添加了两个方法,分别是firstFunc(domain strin

本文探讨了Go语言中struct方法接收者为指针和值的区别,包括对字段值修改的影响、方法包含及接口实现。通过示例代码展示了receiver类型如何影响方法调用和接口实现。
最低0.47元/天 解锁文章
692

被折叠的 条评论
为什么被折叠?



