Why don't changes made to a struct via a method persist?

前端 未结 3 799
半阙折子戏
半阙折子戏 2020-12-20 15:30

I\'m trying to understand why the following test code is not working as expected:

package main

import (
    \"fmt\"
    \"strings\"
)

type Test struct {
           


        
3条回答
  •  天涯浪人
    2020-12-20 16:06

    The AddString method is using a value (copy) receiver. The modification is made to the copy, not the original. A pointer receiver must be used to mutate the original entity:

    package main
    
    import (
            "fmt"
    )
    
    type Test struct {
            someStrings []string
    }
    
    func (t *Test) AddString(s string) {
            t.someStrings = append(t.someStrings, s)
            t.Count() // will print "1"
    }
    
    func (t Test) Count() {
            fmt.Println(len(t.someStrings))
    }
    
    func main() {
            var test Test
            test.AddString("testing")
            test.Count() // will print "0"
    }
    

    Playground


    Output

    1
    1
    

提交回复
热议问题