新手请教个问题,我这里有一个嵌套结构体,结构体中包含一个切片,切片中元素也是一个结构体,结构体中有一个字段的类型为**interface{}**。初始时给这个interface{}的类型赋了string值。后面通过一个一个指针接收的方法去循环修改这个切片中结构体的Uuid字段为int类型值。但是完成后,打印出来发现未被修改。想请教一下代码改怎么修改才能达到目的。
```
package main
import (
"fmt"
)
type Ver struct {
Num int
Uuid interface{}
}
type Index struct {
Line int
Name []Ver
}
type Back struct {
Floor string
Name string
Index Index
}
func (e *Back) change() {
fmt.Println("------------------------------")
fmt.Printf("before change struct is: %+v\n", e)
for _, v := range e.Index.Name {
fmt.Println("v.Uuid is:", v.Uuid)
v.Uuid = 333
fmt.Println("after change v.Uuid is:", v.Uuid)
}
// e.Index.Name = 150
fmt.Printf("after change point: %p\n", e)
fmt.Printf("after change struct is: %+v\n", e)
}
func main() {
a := &Back{"abc","cvb",Index{10, []Ver{Ver{6, "gggg"},Ver{60,"gggg2"}}}}
fmt.Printf("in main a point: %p\n", a)
fmt.Printf("in main struct is: %#v\n", a)
a.change()
fmt.Println("------------------------------")
fmt.Printf("last a struct is: %+v\n", a)
}
```
执行结果如下:
```
in main a point: 0xc00008e040
in main struct is: &main.Back{Floor:"abc", Name:"cvb", Index:main.Index{Line:10, Name:[]main.Ver{main.Ver{Num:6, Uuid:"gggg"}, main.Ver{Num:60, Uuid:"gggg2"}}}}
------------------------------
before change struct is: &{Floor:abc Name:cvb Index:{Line:10 Name:[{Num:6 Uuid:gggg} {Num:60 Uuid:gggg2}]}}
v.Uuid is: gggg
after change v.Uuid is: 333
v.Uuid is: gggg2
after change v.Uuid is: 333
after change point: 0xc00008e040
after change struct is: &{Floor:abc Name:cvb Index:{Line:10 Name:[{Num:6 Uuid:gggg} {Num:60 Uuid:gggg2}]}}
------------------------------
last a struct is: &{Floor:abc Name:cvb Index:{Line:10 Name:[{Num:6 Uuid:gggg} {Num:60 Uuid:gggg2}]}}
```
麻烦!
我找到问题所在了,
在对切片range循环时 for k, v := range []string ,v是一个新的变量不是指向切片中的值的。需要用到切片的下标进行赋值操作。
打扰大家了
#1