Go中的结构实现它的的写法注意事项

下面一个例子:

type Student struct {
    name string
    age  int
}

func (s Student) printAge() {
    fmt.Println(s.age)
}
func (s Student) setAge(age int) {
    s.age = age
}

func main() {

    var P Student = Student{"huang", 15}
    P.setAge(10)
    P.printAge()

这段代码输出多少了,答案是15,那为什么

P.setAge(10)
调用了这个setAge方法,而age还没改变呢?
上述的代码Go没有报错,这就说明代码没有错误,只能说有bug,GO在上面表明只是值传递,假如要实现一个类似Class类型的方法,只有指针去改变了。

type Student struct {
    name string
    age  int
}

func (s *Student) printAge() {
    fmt.Println(s.age)
}
func (s *Student) setAge(age int) {
    s.age = age
}

func main() {

    var P Student = Student{"huang", 15}
    P.setAge(10)
    P.printAge()

}

这样就行。



原文地址:https://www.cnblogs.com/leisure520/p/7745738.html