go - 如何使用从指向结构的指针反射来遍历嵌入式结构

标签 go

我有这个代码:

package main

import (
    "fmt"
    "reflect"
)

type B struct {
    X string
    Y string
}

type D struct {
    B
    Z string
}

func DeepFields(iface interface{}) []reflect.Value {
    fields := make([]reflect.Value, 0)
    ifv := reflect.ValueOf(iface)
    ift := reflect.TypeOf(iface)

    for i := 0; i < ift.NumField(); i++ {
        v := ifv.Field(i)

        switch v.Kind() {
        case reflect.Struct:
            fields = append(fields, DeepFields(v.Interface())...)
        default:
            fields = append(fields, v)
        }
    }

    return fields
}

func main() {
    b := B{"this is X", "this is Y"}
    d := D{b, "this is Z"}
    // fmt.Printf("%#v\n", d)
    fmt.Println(DeepFields(d)) //works fine

    // fmt.Println(DeepFields(&d)) //but I need to pass pointer
}

去 Playground :https://play.golang.org/p/1NS29r46Al

我需要使用指针来完成,请参阅第 44 行。

最佳答案

为了能够发送指针和值元素,您可以将其添加到您的 DeepFields 函数中:

if ift.Kind() == reflect.Ptr {
    ifv = ifv.Elem()
    ift = ift.Elem()
}

修改后的 Playground :https://play.golang.org/p/MgB-W81dYr

关于go - 如何使用从指向结构的指针反射来遍历嵌入式结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46155032/

相关文章:

如果在 const 定义中声明和使用自定义类型,Godoc 不会生成 "const"字段?

go - 执行闭包 goroutine 未能达到预期结果

go - 如何在golang中按索引排序

oracle - 无法使用Oracle db在Golang中构建应用

去读线-> 字符串

go - 同时配置网络设备

arrays - 在 Go 中并行处理数组会产生意想不到的结果

go - 如何使用正则表达式匹配任何重复字符?

git - Go 模块在 go.mod 中用 v0.0.0-<timestamp>-<revision> 替换显式版本

arrays - 如何在 golang 中创建关联映射?