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

问题描述 投票:-1回答:2

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

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:reflect:调用reflect.Value.FieldByName on interface value on line“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

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

所以我的问题是,当结构类型作为接口输入时,如何设置结构的字段?


UPDATE

我发布了一个解决方案作为答案,但我不相信它是否是正确或安全的做事方式。我希望有人可以解释,或发布更好的解决方案。

go go-reflect
2个回答
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


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。

© www.soinside.com 2019 - 2024. All rights reserved.