亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何更新任意go結構的所有字符串字段?

如何更新任意go結構的所有字符串字段?

Go
梵蒂岡之花 2023-08-14 17:16:32
我嘗試編寫一個函數來更新任意結構的所有字符串字段,如下所示:type Student struct {  Name  string  Age   int}func SetStringField(obj interface{}) {    reflect.ValueOf(obj).Elem().FieldByName("Name").SetString("set name")}func main() {  student := Student{    "alice",    12,  }  SetStringField(&student)}func SetStringField2(obj interface{}) {    // Keys := reflect.TypeOf(obj)    Values := reflect.ValueOf(obj)    count := reflect.ValueOf(obj).NumField()    for i := 0; i < count; i++ {        // fieldKey := Keys.Field(i).Name        fieldValue := Values.Field(i)        switch fieldValue.Kind() {        case reflect.String:            // fieldValue.CanSet()==false            fieldValue.SetString("fieldCleanString2 set name")            // panic: reflect: call of reflect.Value.FieldByName on interface Value            // reflect.ValueOf(&obj).Elem().FieldByName(fieldKey).SetString("123")        }    }}func main() {  student := Student{    "alice",    12,  }  SetStringField2(student)}fieldValue.SetString() 得到“恐慌:反射:reflect.flag.mustBeAssignable 使用不可尋址的值”,因為 fieldValue.CanSet()==false。Reflect.ValueOf(&obj).Elem().FieldByName(fieldKey).SetString("fieldCleanString2 set name") 也失敗,得到“恐慌:反射:在接口 Value 上調用reflect.Value.FieldByName”。調用 SetStringField2(&student) 得到“恐慌:反射:在 ptr Value 上調用reflect.Value.NumField”那么,還有其他方法可以完成這項工作嗎?
查看完整描述

2 回答

?
慕桂英4014372

TA貢獻1871條經驗 獲得超13個贊

問題是反射值不可設置。要解決此問題,請從指針創建反射值。


// SetStringField2 sets strings fields on the struct pointed to by ps.

func SetStringField2(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("fieldCleanString2 set name")

        }

    }

}

將指向值的指針傳遞給函數:


student := Student{

    "alice",

    12,

}

SetStringField2(&student)

在操場上運行它



查看完整回答
反對 回復 2023-08-14
?
三國紛爭

TA貢獻1804條經驗 獲得超7個贊

解決方案一:

https://img1.sycdn.imooc.com//64d9f1230001efa005870432.jpg

package service


import (

    "fmt"

    "reflect"

    "testing"

)



func SetStringField2(obj interface{}) {

    Values := reflect.ValueOf(obj).Elem()

    count := reflect.Indirect(reflect.ValueOf(obj)).NumField()

    for i := 0; i < count; i++ {

        fieldValue := Values.Field(i)

        switch fieldValue.Kind() {

        case reflect.String:

            fieldValue.SetString("fieldCleanString2 set name")

        }

    }

}


func TestSetValue(t *testing.T) {


    type Student struct {

        Name string

        Age  int

    }

    student := &Student{

        "alice",

        12,

    }


    SetStringField2(student)


    fmt.Print(student.Name)

}


查看完整回答
反對 回復 2023-08-14
  • 2 回答
  • 0 關注
  • 201 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號