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.

42 lines
955 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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)
}