1.1 什么是方法
通俗的理解为,方法类似于Java类中定义的方法,只能通过该类的实例进行访问,是该类所特有的函数。
它和函数的区别在于方法有一个接收者,给一个函数添加一个接收者,那么它就变成了方法。接收者可以是值接收者,也可以是指针接收者。
1.2 方法的语法
func (t Type) methodName(parameter list)(return list) {
}
示例:
type Employee struct {
name string
salary int
currency string // 货币单位
}
// 定义一个方法,用来展示薪资
func (e Employee) displaySalary() {
fmt.Printf("%s的薪资是%s%d:\n", e.name, e.currency, e.salary)
}
func main() {
fmt.Println("方法..")
e1 := Employee{
name: "zled",
salary: 10000,
currency: "$",
}
e1.displaySalary()
}
/*
zled的薪资是:$10000
*/
1.3 定义相同的方法名
类似于java中方法的重载,但与java不同之处在于,java中两个方法的参数不一致也可以理解为重载,但是go中不行,go中同一方法名同一返回类型只能定义一次,不存在参数不同方法不同的情况。也就是说go中允许定义相同的方法名-唯一的限定条件是,返回值不同,参数必须相同。
type Rectangle struct {
width, height float64
}
type Circle struct {
radius float64
}
func (r Rectangle) area() float64 {
return r.width * r.height
}
//该 method 属于 Circle 类型对象中的方法
func (c Circle) area() float64 {
return c.radius * c.radius * math.Pi
}
func main() {
fmt.Println("方法..")
r1 := Rectangle{12, 2}
r2 := Rectangle{9, 4}
c1 := Circle{10}
c2 := Circle{25}
fmt.Println("Area of r1 is: ", r1.area()) // 长方形面积
fmt.Println("Area of r2 is: ", r2.area())
fmt.Println("Area of c1 is: ", c1.area()) // 圆形面积
fmt.Println("Area of c2 is: ", c2.area())
}
/*
Area of r1 is: 24
Area of r2 is: 36
Area of c1 is: 314.1592653589793
Area of c2 is: 1963.4954084936207
*/
- 虽然method的名字一模一样,但是如果接收者不一样,那么method就不一样
- method里面可以访问接收者的字段
- 调用method通过.访问,就像struct里面访问字段一样
1.3 方法于函数
既然由函数,为什么还要使用方法?
示例: ```go type Employee struct { name string salary int currency string }
/ displaySalary() method converted to function with Employee as parameter / func displaySalary(e Employee) { fmt.Printf(“Salary of %s is %s%d”, e.name, e.currency, e.salary) }
func main() { e := Employee{ name: “Sam Adolf”, salary: 5000, currency: “$”, } displaySalary(e) }
/ Salary of Sam Adolf is $5000 / ``` 之所以有函数和方法的区分在于: