繁体   English   中英

使用反射在结构内迭代切片结构

[英]Iterating slice struct within struct using reflection

我正在努力实现以下目标:

用例:

  • 我有三个结构,我需要将其中的两个与一个进行比较。 (在示例中描述为:a & b 需要与 full 进行比较)
  • 反射用于遍历每个字段,检索字段的名称。 并比较a&full、b&full之间的差异,将结果存储在一个共享结构中。
  • 如果字段等于 World,我们知道它是一个切片结构:我需要检索 Foo 结构中 Bar 切片的第一个索引。 即使变量是一个切片,我知道在这个用例中它的长度总是 1。 检索时,我需要遍历这些字段,就像前面的 if 语句中发生的那样。

示例代码:

type Foo struct {
    Hello string
    World []Bar
}

type Bar struct {
    Fish string
}

type Result struct {
    Field string

    Correct_A  bool
    Distance_A int

    Correct_B  bool
    Distance_B int

    Result []Result
}

func compare_structs() {
    var full, a, b Foo

    // filling in all variables...

    result := []Result{}

    rfx_f := reflect.ValueOf(full)
    rfx_a := reflect.ValueOf(a)
    rfx_b := reflect.ValueOf(b)

    type_result := rfx_f.Type()

    for i := 0; i < rfx_f.NumField(); i++ {
        tmp_res := Result{
            Field: type_result.Field(i).Name,
        }

        if reflect.TypeOf(full).Field(i).Type.Kind() != reflect.Slice {
            value := rfx_f.Field(i).Interface()
            value_a := rfx_a.FieldByName(tmp_res.Field).Interface()
            value_b := rfx_b.FieldByName(tmp_res.Field).Interface()

            // functions to compare the values of this field
            tmp_res.compare(value, value_a, value_b)
            tmp_res.lev(value, value_a, value_b)

            result = append(result, tmp_res)
        } else if tmp_res.Field == "World" {
            /*
                I need to retrieve the first index of the Bar slice within the Foo structure.
                Even though the variable is a slice, I know it will always have a length of 1 in this use-case.
                When retrieved I need to loop over those fields, like what is happening in the previous if statement.
            */
        }

    }
}

您首先需要获取该字段:

wordField:=rfx_f.Field(i)

你知道它是一个切片,所以你索引它来获取第一个元素

item:=wordField.Index(0)

如果索引超出范围,这将导致恐慌。

然后你可以迭代字段:

for fieldIx:=0;fieldIx<item.NumField();fieldIx++ {
    field:=item.Field(fieldIx)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM