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

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

如何給reflect Field()賦值?

如何給reflect Field()賦值?

Go
GCT1015 2023-07-26 13:18:12
我遇到了這樣的問題。我需要比較兩個結構,如果它們的類型和字段名稱相同。將值從 sour 分配給 dist。我編寫了一些代碼,但在這里我可以分配 Reflect.Field() 值。你可以幫幫我嗎?我在下面創建了測試import (    "reflect"    "testing")func Assign(sour interface{}, dist interface{}) uint {    counter := 0    source  := reflect.ValueOf(sour)    target  := reflect.ValueOf(dist)    typeSource := reflect.TypeOf(sour)    typeTarget := reflect.TypeOf(dist)    for i:=0; i<source.NumField(); i++{        for j:=0; j<target.NumField();j++{            if (typeSource.Field(i).Type==typeTarget.Field(j).Type && typeSource.Field(i).Name==typeTarget.Field(j).Name){                counter = counter + 1                target.FieldByName(typeSource.Field(i).Name).Set(source.Field(i))            }        }    }    return uint(counter)}func TestAssign(t *testing.T) {    type A struct {        A string        B uint        C string    }    type B struct {        AA string        B  int        C  string    }    var (        a = A{            A: "Тест A",            B: 55,            C: "Test C",        }        b = B{            AA: "OKOK",            B:  10,            C:  "FAFA",        }    )    result := Assign(a, b)    switch true {    case b.B != 10:        t.Errorf("b.B = %d; need to be 10", b.B)    case b.C != "Test C":        t.Errorf("b.C = %v; need to be  'Test C'", b.C)    case result != 1:        t.Errorf("Assign(a,b) = %d; need to be 1", result)    }}
查看完整描述

1 回答

?
MMTTMM

TA貢獻1869條經驗 獲得超4個贊

為了Assign工作,第二個參數必須是可尋址的,即您需要傳遞一個指向結構值的指針。


// the second argument MUST be a pointer to the struct

Assing(source, &target)

然后您需要稍微修改您的實現,Assign因為指針沒有文件。您可以使用該Elem()方法獲取指針指向的結構體值。


func Assign(sour interface{}, dist interface{}) uint {

    counter := 0

    source := reflect.ValueOf(sour)


    // dist is expected to be a pointer, so use Elem() to

    // get the type of the value to which the pointer points

    target := reflect.ValueOf(dist).Elem()


    typeSource := reflect.TypeOf(sour)


    typeTarget := target.Type()

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

        for j := 0; j < target.NumField(); j++ {

            if typeSource.Field(i).Type == typeTarget.Field(j).Type && typeSource.Field(i).Name == typeTarget.Field(j).Name {

                counter = counter + 1

                target.FieldByName(typeSource.Field(i).Name).Set(source.Field(i))


            }

        }

    }


    return uint(counter)

}


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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