为了账号安全,请及时绑定邮箱和手机立即绑定

golang:如何在界面中检查导出的字段

golang:如何在界面中检查导出的字段

Go
慕工程0101907 2022-11-08 15:23:11
精简版:import (    "fmt"    "reflect")type StatusVal inttype Foo struct {    Name string    Age  int    art  string}func ListFields(a interface{}) {    v := reflect.ValueOf(a).Elem()    fmt.Printf(" Kind: %+v \n", v.Type())    for _, f := range reflect.VisibleFields(v.Type()) {        if f.IsExported() {            fmt.Printf(" Kind: %+v \n", f)        } else {            fmt.Printf(" Kind: %s \n", f.Name)        }    }}func main() {    var x Foo    ListFields(&x)}这段代码有效,但我真正需要的是var x []Foo,我找不到一种方法让它工作并在结构切片的字段中检查 IsExported。长版:我正在寻找生成一个通用的 sqlToStruct 函数,我遇到了这个很棒的答案: Generalizing *sql.Rows Scan in Go我没有在那里回复的声誉。唯一的问题是,如果我的结构有任何未导出的字段,它就会恐慌,我想检查一下并返回一个要处理的错误,而不是让它恐慌。另外:我在 go 中编码的时间很短,如果我遗漏了一些绝对明显的东西,请理解我来自哪里,并抱歉。
查看完整描述

1 回答

?
哆啦的时光机

TA贡献1779条经验 获得超6个赞

func ListFields(a interface{}) {

    rt := reflect.TypeOf(a) // take type of a

    if rt.Kind() == reflect.Ptr {

        rt = rt.Elem() // use Elem to get the pointed-to-type

    }

    if rt.Kind() == reflect.Slice {

        rt = rt.Elem() // use Elem to get type of slice's element

    }

    if rt.Kind() == reflect.Ptr { // handle input of type like []*StructType

        rt = rt.Elem() // use Elem to get the pointed-to-type

    }

    if rt.Kind() != reflect.Struct {

        return

    }


    fmt.Printf(" Kind: %+v \n", rt)

    for _, f := range reflect.VisibleFields(rt) {

        if f.IsExported() {

            fmt.Printf(" Kind: %+v \n", f)

        } else {

            fmt.Printf(" Kind: %s \n", f.Name)

        }

    }

}

https://go.dev/play/p/0J3VXmFPe87


查看完整回答
反对 回复 2022-11-08
  • 1 回答
  • 0 关注
  • 128 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号