go语言---方法

go语言的方法:

  1. 方法与函数语法基本类似,区别是函数属于包,通过包调用函数,包在物理层面上就是文件夹;而方法属于结构体,通过结构体变量来调用;
  2. 方法在定义的时候需要指明这个方法属于哪个结构体;定义语法:
func (变量名 结构体类型) 方法名(参数列表) 返回值列表 {
	方法体
}
  1. 在使用结构体的方法时,如果需要改变结构体属性的值,需要在定义方法时,传递结构体的指针,也就是在结构体前面加*, 即:
func (变量名 *结构体类型) 方法名(参数列表) 返回值列表 {
	方法体
}
  1. 上面的变量名可以理解为python方法里面的self,谁调用这个方法,它就表示谁;


package main

import "fmt"

// 结构体
type Student struct {
	Name string  // 姓名
	score int  // 分数

}

// 定义一个study的方法,该方法属于Student结构体,假如学习1次加1分, 由于Student是值类型,分数不变
func (s Student) study()  {
	fmt.Printf("%s 努力学习中...  ", s.Name)
	s.score += 1
	fmt.Println("分数加1,当前分数为:", s.score)

}

// 定义一个study的方法,该方法属于Student结构体,假如学习1次加1分, 使用*Student,操作该内存空间
func (s *Student) study2()  {
	fmt.Printf("%s 努力学习中...  ", s.Name)
	s.score += 1
	fmt.Println("分数加1,当前分数为:", s.score)

}

func main() {
	s1 := Student{"张三", 55}  // 初始分数50
	s1.study()
	s1.study()
	s1.study()
	s1.study()
	s1.study()
	/*
	张三 努力学习中...  分数加1,当前分数为: 56
	张三 努力学习中...  分数加1,当前分数为: 56
	张三 努力学习中...  分数加1,当前分数为: 56
	张三 努力学习中...  分数加1,当前分数为: 56
	张三 努力学习中...  分数加1,当前分数为: 56
	 */

	// 上面可以发现,多次调用,分数一直是56,原因是结构体是值类型,需要在定义方法时,使用结构体的指针, 即(s *Student)
	s2 := Student{"李四", 55}
	s2.study2()
	s2.study2()
	s2.study2()
	s2.study2()
	s2.study2()
	/*
	李四 努力学习中...  分数加1,当前分数为: 56
	李四 努力学习中...  分数加1,当前分数为: 57
	李四 努力学习中...  分数加1,当前分数为: 58
	李四 努力学习中...  分数加1,当前分数为: 59
	李四 努力学习中...  分数加1,当前分数为: 60
	 */

}

发布了22 篇原创文章 · 获赞 1 · 访问量 1829

猜你喜欢

转载自blog.csdn.net/weixin_42677653/article/details/105176574