36_方法集的使用

所谓方法集,就是go编译器,可以根据 传递的接收者(receiver)类型,自动转换成所需的类型


代码如下:
package main
 
import "fmt"
 
type Student struct {
	//和变量定义不同,不要写var关键字
	Id   int
	Name string
	Sex  byte
	Age  int
	Addr string
}
 
func (s Student) PrintValue() {
	fmt.Println("该方法为值传递")
 
}
func (s *Student) Printpointer() {
	s.Name = "steven"
	fmt.Println("该方法为引用传递")
 
}
func main() {
	
 
	//类型为T的方法集
	s1 := Student{1, "zhao", 'm', 24, "js"}
 
	//下面两者调用都可以
	s1.Printpointer() //该方法为引用传递
	//先把s1转换成(&s1),然后是(&s1).printpointer
	(&s1).Printpointer() //该方法为引用传递
 
	//下面两种方法类似
	s1.PrintValue()
	(&s1).PrintValue() //也是接收者先进行类型转换,然后在调用方法
 
	//类型为*T 的方法集
	var s2 *Student = &Student{2, "zhao", 'm', 24, "js"}
	(*s2).PrintValue()
	s2.PrintValue()
	\
	s2.Printpointer()
}

猜你喜欢

转载自www.cnblogs.com/zhaopp/p/11565367.html
36
今日推荐