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

用例:

  • 我有三个 struct ,我需要比较其中的两个和一个.(在示例中描述为:a和b需要与full进行比较)
  • 反射用于在每个字段上循环,检索字段的名称.比较a和;完整,b&完整,将结果存储在共享 struct 中.
  • 如果场等于世界,我们知道它是一个切片 struct :

示例代码:

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)

如果索引超出范围,这将导致panic .

然后可以迭代字段:

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

Go相关问答推荐

出口上下文值密钥的安全方法?

如何在AWS SDK Go v2 STS上正确使用重试

Go Regexp:匹配完整的单词或子字符串,或者根本不匹配

将类型定义为泛型类型实例化

如何在Golang中获取mp3文件的持续时间?

确定果朗CSV行中的字节数

Redis:尽管数据存在,但 rdb.Pipelined 中出现redis:nil错误

错误!在为 age-viewer-go 运行 wails dev 或 wails build 命令时

具有两个参数的动态规划:天数和优惠券

无法将 graphql-ws 连接到 gqlgen

如果值为 false,gRPC 不返回布尔值

Go http.FileServer 给出意外的 404 错误

从数据库中带有 imageurl 的文件夹中获取图像,并在我的浏览器中用 golang 中的 echo 显示

为什么 reflect.TypeOf(new(Encoder)).Elem() != reflect.TypeOf(interfaceVariable)?

我相信我正确地在 sRGB 和线性 RGB 之间进行了转换,那么为什么深色的结果看起来更糟呢?

未定义 protoc protoc-gen-go 时间戳

如何使用 Status 字段创建 Kubernetes 对象?

无法在 GORM 中排序

如何优雅地映射到 Go 中返回可变长度数组的方法?

Go:如何通过 GIN-Router 从 AWS S3 将文件作为二进制流发送到浏览器?