修改接口{} golang的数组

时间:2015-01-20 20:52:29

标签: go

这种类型的断言,def-referencing一直让我发疯。所以我有一个Key string / Value interface{}对的嵌套结构。存储在Value中的是[]interface,我想修改每个值。下面是创建Bar数组并将其传递到ModifyAndPrint函数的示例,该函数应修改顶级结构。我遇到的问题是写的并没有实际修改z的内容,我不能做q := z.([]interface{})[i].(Bar)&

有办法做到这一点吗?如果是这样,我错过了什么组合?

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

1 个答案:

答案 0 :(得分:4)

程序正在修改接口{}中值的副本。实现目标的一种方法是将修改后的值分配回切片:

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