You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
package main
|
|
|
|
|
|
|
|
|
|
import "fmt"
|
|
|
|
|
|
|
|
|
|
// Person
|
|
|
|
|
/**
|
|
|
|
|
Go语言中的方法(Method)是一种作用于特定类型变量的函数。
|
|
|
|
|
这种特定类型变量叫做接收者(Receiver)。
|
|
|
|
|
接收者的概念就类似于其他语言中的this或者 self。
|
|
|
|
|
*/
|
|
|
|
|
type Person struct {
|
|
|
|
|
name string
|
|
|
|
|
age int
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func newPerson2(name string, age int) *Person {
|
|
|
|
|
return &Person{
|
|
|
|
|
name: name,
|
|
|
|
|
age: age,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Dream 方法
|
|
|
|
|
func (p Person) Dream() {
|
|
|
|
|
fmt.Printf("%s 好好学习\n", p.name)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
//指针类型接收者 =>
|
|
|
|
|
//1.因为结构体是值类型,当需要修改接收者中的值的时候,需要使用指针类型的接收者
|
|
|
|
|
//2.接收者是拷贝代价比较大的大对象
|
|
|
|
|
//3.保证一致性,如果有某个方法使用了指针接收者,那么其他的方法也应该使用指针接收者。
|
|
|
|
|
func (p *Person) setAge(nAge int) {
|
|
|
|
|
p.age = nAge
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
|
p1 := newPerson2("song", 18)
|
|
|
|
|
p1.Dream()
|
|
|
|
|
p1.setAge(20)
|
|
|
|
|
fmt.Printf("p1: %v", p1.age)
|
|
|
|
|
}
|