//指针
a :=10//int类型
b :=&a //int类型 int指针
fmt.Println(a,&a)//10 0xc0000b2008
fmt.Println(b)// 0xc0000b2008//指针变量
c :=*b //*是获取指针对应的变量
fmt.Println(c)//10//指针类型数据必须是有初始化值的var a *int//nil*a =100//无法对一个空指针赋值
fmt.Println(a)//new 函数 指针类型的初始化 各个类型的 零值(new用于类型的内存分配,并且内存对应的值为类型零值,返回的是指向类型的指针)
a :=new(int)
fmt.Println(a)//0xc0000b2008
fmt.Println(*a)//0bool:=new(bool)
fmt.Println(bool)//0xc000012078
fmt.Println(*bool)//false//make只用于slice、map以及channel的初始化,返回的还是这三个引用类型本身
//方法 : 是一种作用于特定类型变量的函数。这种特定类型变量叫做接收者(Receiver)。接收者的概念就类似于其他语言中的this或者 selffunc(接收者变量 接收者类型) 方法名(参数列表)(返回参数){
函数体
}
接收者变量:接收者中的参数变量名在命名时,官方建议使用接收者类型名称首字母的小写,而不是self、this之类的命名。例如,Person类型的接收者变量应该命名为 p,Connector类型的接收者变量应该命名为c等。
接收者类型:接收者类型和参数类似,可以是指针类型和非指针类型。
方法名、参数列表、返回参数:具体格式与函数定义相同。
package main
import"fmt"//结构体type person struct{
name, city string
age int8}//构造函数funcnewPerson(name, city string, age int8)*person {//返回 指针类型return&person{//因为返回指针类型 所以 返回 取地址
name: name,
city: city,
age: age,}}//方法func(p person)Dream(){
fmt.Printf("%s我爱你", p.name)}funcmain(){
p :=newPerson("lwl","杭州",24)
p.Dream()//调用}
指针类型的接收者
package main
import"fmt"type person struct{
name, city string
age int8}funcnewPerson(name, city string, age int8)*person {return&person{
name: name,
city: city,
age: age,}}//指针类型的接收者func(p *person)setAge(){
p.age =30}funcmain(){
p :=newPerson("lwl","杭州",24)
fmt.Println(p.age)//24
p.setAge()
fmt.Println(p.age)//30}
值类型的接收者
package main
import"fmt"type person struct{
name, city string
age int8}funcnewPerson(name, city string, age int8)*person {return&person{
name: name,
city: city,
age: age,}}//指针类型的接收者func(p *person)setAge(){
p.age =30}//值类型的接收者func(p person)setAge1(newAge int8){
p.age = newAge
}funcmain(){
p :=newPerson("lwl","杭州",24)
fmt.Println(p.age)//24
p.setAge()
fmt.Println(p.age)//30
p.setAge1(50)
fmt.Println(p.age)//30}
总结:
需要修改接收者中的值
接收者是拷贝代价比较大的大对象
保证一致性,如果有某个方法使用了指针接收者,那么其他的方法也应该使用指针接收者。