3

This type assertion, def-referencing has been driving me crazy. So I have a nested structure of Key string / Value interface{} pairs. Stored in the Value is an []interface which I want to modify each of the values. Below is an example of creating an array of Bar and passing it into the ModifyAndPrint function which should modify the top level structure. The problem that I come accross is as written it doesn't actually modify the contents of z, and I can't do a q := z.([]interface{})[i].(Bar) or & thereof.

Is there a way to do this? If so, what combination did I miss?

package main

import "fmt"

type Bar struct {
   Name string
   Value int
}

func ModifyAndPrint(z interface{}){
    fmt.Printf("z before: %v\n", z)
    for i, _ := range(z.([]interface{})) {      
        q := z.([]interface{})[i]
        b := (q).(Bar)
        b.Value = 42
        fmt.Printf("Changed to: %v\n", b)
    }
    fmt.Printf("z after: %v\n", z)
}

func main() {       
    bars := make([]interface{}, 2)
    bars[0] = Bar{"a",1}
    bars[1] = Bar{"b",2}

    ModifyAndPrint(bars)    
}

https://play.golang.org/p/vh4QXS51tq

2
  • stackoverflow.com/questions/15945030/… Commented Jan 20, 2015 at 20:59
  • I'm confused by that link. It seems like it says to use indexing, which I am doing. Commented Jan 20, 2015 at 21:14

1 Answer 1

7

The program is modifying a copy of the value in the interface{}. One way to achieve your goal is to assign the modified value back to the slice:

for i, _ := range(z.([]interface{})) {      
    q := z.([]interface{})[i]
    b := (q).(Bar)
    b.Value = 42
    z.([]interface{})[i] = b
    fmt.Printf("Changed to: %v\n", b)
}

playground example

Sign up to request clarification or add additional context in comments.

1 Comment

That works, but is there a better way that doesn't involve creating a modified element and assigning back? Can I just work with the original value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.