douye1876 2018-10-13 21:55
浏览 77
已采纳

为什么函数执行后值会改变?

I'm currently teaching myself Go, and I'm having trouble understanding a certain behavior:

package main

import (
    "fmt"
)

type List struct {
    n int
}

func (l List) Increment() {
    l.n += 1
    l.LogState() // size: 1
}

func (l List) LogState() {
    fmt.Printf("size: %v
", l.n)
}

func main() {
    list := List{}
    list.Increment()

    fmt.Println("----")
    list.LogState() // size: 0
}

https://play.golang.org/p/-O24DiNPkxx

LogState is executed twice. The initial time, during the Increment call, it prints size: 1 but after Increment has returned it prints size: 0. Why are those values different?

展开全部

  • 写回答

2条回答 默认 最新

  • douba3378 2018-10-13 23:03
    关注

    The reason your nodes are not added to the original linkedList because you are not using pointer to the struct. So even if the Increment function in your example code changes the value. The copy of the struct is changed not the actual struct.

    You can declare methods with pointer receivers. This means the receiver type has the literal syntax *T for some type T. (Also, T cannot itself be a pointer such as *int.)

    If you want to change the linkedlistNode struct counter to show the nodes added to the list you should be using a pointer type receiver on both methdos working to modify the linked list as:

    func (l *LinkedList) AddInitialValue(v interface{})
    func (l *LinkedList) LogState()
    

    And Inside the main pass an address to the linkedList to use those pointer type receivers as:

    func main() {
        list :=  &LinkedList{}
        list.AddInitialValue(9)
    
        fmt.Println("----")
        list.LogState() // size: 0
    }
    

    Working Code Go playground

    Note:-

    There are two reasons to use a pointer receiver.

    • To modify the value that its receiver points to.
    • To avoid copying the value on each method call. This can be more efficient if the receiver is a large struct

    For more information go through Method Sets

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部