-1

I defined a struct and have fields in them one of the fields is map[string]interface{} type. I've instantiated the struct globally, I've created a table struct and looping through it. In each loop I'm assigning the instantiated global struct to local variable and then changing the value of Id field in the struct if certain field in present in map. Once the value of Id is changed and loop goes into next iteration the modified for Id field still exists.

type transaction struct {
    Name string
    Id   string
    M    map[string]interface{}
}

var txn1 = transaction{
    Name: "Akshith",
    Id:   "123",
    M: map[string]interface{}{
        "item": "abc",
    },
}

func changeId(txn *transaction) {
    if _, present := txn.M["check"]; present {
        txn.Id = "456"
    }
}

func main() {

    txns := []struct {
        Change bool
        Id     string
    }{
        {
            Change: false,
        },
        {
            Change: true,
            Id:     "456",
        },
        {
            Change: false,
        },
    }

    for i, txs := range txns {
        var txn2 = txn1

        if txs.Change == true {
            txn2.M["check"] = true
        }
        changeId(&txn2)
        fmt.Println("*** index : ", i)
        fmt.Println("**** id2 : ", txn2)
        fmt.Println("**** id1 : ", txn1)

    }
}

output : *** index : 0 **** id2 : {Akshith 123 map[item:abc]} **** id1 : {Akshith 123 map[item:abc]} *** index : 1 **** id2 : {Akshith 456 map[check:true item:abc]} **** id1 : {Akshith 123 map[check:true item:abc]} *** index : 2 **** id2 : {Akshith 456 map[check:true item:abc]} **** id1 : {Akshith 123 map[check:true item:abc]}

In the third iteration there shouldn't be check field in the map and Id value should be 123

  • Your `var txn2 = txn1` makes a shallow copy of `txn1`. The embedded `M` member still points to the same underlying map. In other words, that assignment does not make a copy of the map. – Kurtis Rader Aug 13 '23 at 00:08

0 Answers0