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

无法在任意 Go 结构中使用反射更新嵌套字符串字段

无法在任意 Go 结构中使用反射更新嵌套字符串字段

Go
皈依舞 2022-11-15 17:09:50
我正在尝试使用 golang 中的反射为任意结构更新结构及其子字段中的所有字符串字段,如下所示:package mainimport (    "fmt"    "reflect"    "strings")func main() {    type Inner struct {        In1 string        In2 []string    }    type Type struct {        Name  string        Names []string        NewSt Inner    }    a := Type{        Name:  " [ (Amir[ ",        Names: nil,        NewSt: Inner{            In1: " [in1",            In2: []string{"  [in2( "},        },    }    trims(&a)    fmt.Printf("%#v\n", a)}func trim(str string) string {    return strings.TrimSpace(strings.Trim(str, "[](){}, "))}func trims(ps interface{}) {    v := reflect.ValueOf(ps).Elem() // Elem() dereferences pointer    for i := 0; i < v.NumField(); i++ {        fv := v.Field(i)        switch fv.Kind() {        case reflect.String:            fv.SetString(trim(fv.String()))        case reflect.Struct:            in := fv.Interface()            trims(&in)        }    }}但我感到恐慌:反射:在结构值错误上调用 reflect.Value.Elem。我该如何解决它,或者有什么更好的方法可以做到这一点?
查看完整描述

1 回答

?
波斯汪

TA贡献1811条经验 获得超4个赞

func trims(ps interface{}) {

    v := reflect.ValueOf(ps)

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

        v = v.Elem() // Elem() dereferences pointer

    }

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

        panic("not struct")

    }

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

        fv := v.Field(i)

        switch fv.Kind() {

        case reflect.String:

            fv.SetString(trim(fv.String()))

        case reflect.Struct:

            // use Addr() to get an addressable

            // value of the field

            in := fv.Addr().Interface()


            // do not use &in, that evaluates

            // to *interface{}, that's almost

            // NEVER what you want

            trims(in)

        case reflect.Slice:

            if fv.Type().Elem().Kind() == reflect.String {

                for i := 0; i < fv.Len(); i++ {

                    fv.Index(i).SetString(trim(fv.Index(i).String()))

                }

            }

        }

    }

}

https://go.dev/play/p/JkJTJzTckNA


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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