首页 > 其他 > 详细

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

时间:2017-10-28 00:56:01      阅读:251      评论:0      收藏:0      [点我收藏+]

下面一个例子:

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

}

这样就行。



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

原文:http://www.cnblogs.com/leisure520/p/7745738.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!