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

前端 未结 3 802
半阙折子戏
半阙折子戏 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:04

    Your functions are defined on the object themselves rather than a pointer to the object.

    func (this Test) AddString(s string) {
        this.someStrings = append(this.someStrings, s)
        this.Count() // will print "1"
    }
    

    The function above is defined on the concrete data. This means that when you call the function, the value of this is passed in as a copy of the data. So any mutations you do to this are done on the copy (in this case, the mutation is changing the pointer that 'someStrings' points to. We can rewrite the same function defined on a pointer of Test as jnml did:

    func (this *Test) AddString(s string) {
        this.someStrings = append(this.someStrings, s)
        this.Count() // will print "1"
    }
    

    As you can see, the function definition is (this *Test) instead of (this Test). This means that the variable this is passed by reference, and any mutations that take place are mutations performed on the original object.

提交回复
热议问题