【问题标题】:Pass by reference nested structures through reflection通过反射传递引用嵌套结构
【发布时间】:2014-07-31 07:34:41
【问题描述】:
type Client struct {
    Id                int
    Age               int
    PrimaryContact    Contact
    Name              string
}

type Contact struct {
    Id        int
    ClientId  int
    IsPrimary bool
    Email     string
}

以上是示例代码;我想要实现的是以下内容: - 使用反射循环遍历所有客户端结构字段 - 为每个“原始”字段使用反射设置一个默认值 - 对于每个结构字段使用递归来应用上述步骤

问题在于,当自省 PrimaryContact 字段并且尝试为其任何字段设置值时,我最终会出现以下恐慌:

reflect.Value.Set 使用不可寻址的值

如果我没记错的话,原因是 PrimaryContact 是按值而不是按引用传递的,因此当我在其任何字段上调用 ​​Set 方法时,它会更改副本上的字段值,而不是实际参数上的字段值。我该如何克服这个问题?如何使用反射通过引用将 PrimaryContact 字段传递给我的方法?

【问题讨论】:

  • 显示代码你做了什么。这是可行的。而且很可能您不是传递了Contact,而是传递了reflect.Values。请注意,Go 中的每个调用都是按值调用的,在 Go 中没有按引用调用。
  • 是的,这是我的问题,事实上我正在传递 reflect.Values,这是错误的做法。我将尝试略读代码,目前它引用了其他内容。
  • 我实际上在做的是传递 reflect.Value 接口。

标签: reflection go


【解决方案1】:

我认为这是一种练习反思的有趣练习。

两个指针:

  • 要设置结构的字段值,您必须将其作为指针传递
  • 要获取结构字段的指针值,请使用Value.Addr()

工作解决方案:

package main

import (
    "fmt"
    "reflect"
    "errors"
)

type Client struct {
    Id                int
    Age               int
    PrimaryContact    Contact
    Name              string
}

type Contact struct {
    Id        int
    ClientId  int
    IsPrimary bool
    Email     string
}

func SetDefault(s interface{}) error {
    return setDefaultValue(reflect.ValueOf(s))
}

func setDefaultValue(v reflect.Value) error {

    if v.Kind() != reflect.Ptr {
        return errors.New("Not a pointer value")
    }

    v = reflect.Indirect(v)
    switch v.Kind() {
        case reflect.Int:
            v.SetInt(42)
        case reflect.String:
            v.SetString("Foo")
        case reflect.Bool:
            v.SetBool(true)
        case reflect.Struct:
            // Iterate over the struct fields
            for i := 0; i < v.NumField(); i++ {
                err := setDefaultValue(v.Field(i).Addr())
                if err != nil {
                    return err
                }
            }       

        default:
            return errors.New("Unsupported kind: " + v.Kind().String())

    }

    return nil  
}


func main() {
    a := Client{}
    err := SetDefault(&a)
    if err != nil {
        fmt.Println("Error: ", err)
    } else {
        fmt.Printf("%+v\n", a)
    }
}

输出:

{Id:42 Age:42 PrimaryContact:{Id:42 ClientId:42 IsPrimary:true Email:Foo} Name:Foo}

游乐场: http://play.golang.org/p/-Mpnb7o4vl

【讨论】:

    【解决方案2】:

    我认为您只需要使用value.Addr(),它会为您提供对联系人的引用。 Full example is here.

    func main() {
        x := Client{PrimaryContact:Contact{}}
        v := reflect.ValueOf(&x)
        fmt.Println("v type:", v.Type(), ", kind:", v.Kind())
        f := v.Elem().FieldByName("PrimaryContact")
        fmt.Println("f type:", f.Type(), ", kind:", f.Kind())
        p := f.Addr()
        fmt.Println("p type:", p.Type(), ", kind:", p.Kind())
        p.Elem().FieldByName("Id").SetInt(1)
        fmt.Println("Contact Id:", x.PrimaryContact.Id)
    }`
    

    输出:

    v type: *main.Client , kind: ptr
    f type: main.Contact , kind: struct
    p type: *main.Contact , kind: ptr
    Contact Id: 1
    

    【讨论】:

      猜你喜欢
      • 2013-06-04
      • 2013-05-12
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 2021-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多