go语言的方法:
- 方法与函数语法基本类似,区别是函数属于包,通过包调用函数,包在物理层面上就是文件夹;而方法属于结构体,通过结构体变量来调用;
- 方法在定义的时候需要指明这个方法属于哪个结构体;定义语法:
func (变量名 结构体类型) 方法名(参数列表) 返回值列表 {
方法体
}
- 在使用结构体的方法时,如果需要改变结构体属性的值,需要在定义方法时,传递结构体的指针,也就是在结构体前面加*, 即:
func (变量名 *结构体类型) 方法名(参数列表) 返回值列表 {
方法体
}
- 上面的变量名可以理解为python方法里面的self,谁调用这个方法,它就表示谁;
package main
import "fmt"
type Student struct {
Name string
score int
}
func (s Student) study() {
fmt.Printf("%s 努力学习中... ", s.Name)
s.score += 1
fmt.Println("分数加1,当前分数为:", s.score)
}
func (s *Student) study2() {
fmt.Printf("%s 努力学习中... ", s.Name)
s.score += 1
fmt.Println("分数加1,当前分数为:", s.score)
}
func main() {
s1 := Student{"张三", 55}
s1.study()
s1.study()
s1.study()
s1.study()
s1.study()
s2 := Student{"李四", 55}
s2.study2()
s2.study2()
s2.study2()
s2.study2()
s2.study2()
}