douye1876 2018-10-14 05: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-14 07: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 PointNet++的onnx模型只能使用一次
  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。