go 结构体方法和结构体指针方法 (&p1).SetV2 也可以简写成 p1.SetV2
package main
import (
"fmt"
)
type People struct {
Name string
Country string
}
func (p People)Print(){
fmt.Printf("name=%s country=%s\n",p.Name,p.Country)
}
func (p People)Set(name string, country string){
p.Name = name
p.Country = country
fmt.Printf("Set name=%s country=%s\n",p.Name,p.Country)
}
func (p *People)SetV2(name string, country string){
fmt.Printf("SetV2 before name=%s country=%s\n",p.Name,p.Country)
p.Name = name
p.Country = country
fmt.Printf("SetV2 after name=%s country=%s\n",p.Name,p.Country)
}
func main(){
var p1 People = People{
Name :"people01",
Country :"China",
}
p1.Print()
p1.Set("people02","中国1")
p1.Print()
p1.SetV2("people04","中国4")
p1.Print()
(&p1).SetV2("people02","中国2") //(&p1).SetV2 也可以简写成 p1.SetV2
p1.Print()
p1.SetV2("people03","中国3")
p1.Print()
}
输出:
name=people01 country=China
Set name=people02 country=中国1
name=people01 country=China
SetV2 before name=people01 country=China
SetV2 after name=people04 country=中国4
name=people04 country=中国4
SetV2 before name=people04 country=中国4
SetV2 after name=people02 country=中国2
name=people02 country=中国2
SetV2 before name=people02 country=中国2
SetV2 after name=people03 country=中国3
name=people03 country=中国3
写入自己的博客中才能记得长久