问题背景
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
,还添加了两个方法,分别是firstFun