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

报告相同问题?