无法设置键入为接口的结构的字段{}

时间:2018-09-01 01:22:39

标签: go go-reflect

我一直在努力使用反射包装。下面的代码符合我的期望:

package main

import (
  "reflect"
  "log"
)
type Car struct {
  Model string
}
type Person struct {
  Name string
  Cars []Car
}

func ModifyIt(parent interface{},fieldName string, val interface{}) {
  slice := reflect.ValueOf(parent).Elem()
  nth := slice.Index(0)
  //row := nth.Interface() // this line causes errors
  row := nth.Interface().(Person)
  elem := reflect.ValueOf(&row).Elem()
  field := elem.FieldByName(fieldName)
  log.Println(field.CanSet())

}

func main() {

  p := []Person{Person{Name:"john"}}
  c := []Car{Car{"corolla"},Car{"jetta"}}

  ModifyIt(&p,"Cars",&c)
}

但是,如果我将row := nth.Interface().(Person)行替换为row := nth.Interface(),即删除了类型断言,那么我会得到错误:

  

panic:反射:接口Value上对reflect.Value.FieldByName的调用   在行“ field:= elem.FieldByName(fieldName)

最近几个小时,我尝试了很多其他操作,例如尝试对其他一些变量进行reflect.TypeOf()reflect.Indirect()等操作,但均未成功。

我已经阅读了其他一些类似问题:

reflect: call of reflect.Value.FieldByName on ptr Value

Set a struct field with field type of a interface

Golang reflection: Can't set fields of interface wrapping a struct

他们似乎暗示我对指针或接口的工作方式没有很好的了解。

所以我的问题是,当将结构键入为接口时,如何设置结构的字段?


更新

我发布了一个解决方案作为答案,但是我对这是正确还是安全的处理方式没有信心。我希望有人可以解释或发布更好的解决方案。

2 个答案:

答案 0 :(得分:2)

尝试一下:

func ModifyIt(slice interface{}, fieldName string, newVal interface{}) {
    // Create a value for the slice.
    v := reflect.ValueOf(slice)

    // Get the first element of the slice.
    e := v.Index(0)

    // Get the field of the slice element that we want to set.
    f := e.FieldByName(fieldName)

    // Set the value!
    f.Set(reflect.ValueOf(newVal))
}

这样称呼它:

p := []Person{Person{Name: "john"}}
c := []Car{Car{"corolla"}, Car{"jetta"}}
ModifyIt(p, "Cars", c)

请注意,调用将直接传递切片,而不是使用指向切片的指针。不需要指针,这会增加额外的复杂性。

Run it on the Playground

答案 1 :(得分:0)

碰巧的是,我终于有了工作。

我用很少的押韵或理由拼凑了一堆随机阅读的东西。我什至尝试在Golang网站上阅读《反射定律》,但我认为我对它与为什么我无法设置类型为interface{}的变量的关系没有很好的了解。总的来说,我还是不明白自己的所作所为。

我在下面的解决方案中满是注释,表明我感到困惑,并且对我是否正确或安全地执行操作缺乏信心。

package main

import (
  "reflect"
  "log"
)
type Car struct {
  Model string
}
type Person struct {
  Name string
  Cars []Car
}

func ModifyIt(parent interface{},fieldName string, val interface{}) {
  log.Println(parent)
  slice := reflect.ValueOf(parent).Elem()
  nth := slice.Index(0)
  row := nth.Interface()
  log.Println(nth.CanSet()) // I can set this nth item

  // I think I have a to make a copy, don't fully understand why this is necessary
  newitem := reflect.New(reflect.ValueOf(row).Type())
  newelem := newitem.Elem()
  field := newelem.FieldByName(fieldName)

  // I need to copy the values over from the old nth row to this new item
  for c:=0; c<nth.NumField(); c++ {
    newelem.Field(c).Set(reflect.Indirect(nth.Field(c)))
  }

  // now I can finally set the field for some reason I don't understand
  field.Set(reflect.ValueOf(val).Elem())

  // now that newitem has new contents in the field object, I need to overwrite the nth item with new item
  // I don't know why I'm doing it, but I'll do it
  // I also don't fully understand why I have to use Indirect sometimes, and not other times...it seems interchangeable with ValueOf(something).Elem(), I'm confused....
  nth.Set(reflect.Indirect(newitem))

}

func main() {

  p := []Person{Person{Name:"john"}}
  c := []Car{Car{"corolla"},Car{"jetta"}}

  ModifyIt(&p,"Cars",&c)
  // now parent is up to date, although I have no idea how I got here.
  log.Println(p)
}

如果任何人都可以发布更好的答案来消除我的困惑,那将是很棒的。我一直很难学习golang。