猿问

如何给reflect Field()赋值?

我遇到了这样的问题。我需要比较两个结构,如果它们的类型和字段名称相同。将值从 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)

    }

}


GCT1015
浏览 118回答 1
1回答

MMTTMM

为了Assign工作,第二个参数必须是可寻址的,即您需要传递一个指向结构值的指针。// the second argument MUST be a pointer to the structAssing(source, &target)然后您需要稍微修改您的实现,Assign因为指针没有文件。您可以使用该Elem()方法获取指针指向的结构体值。func Assign(sour interface{}, dist interface{}) uint {&nbsp; &nbsp; counter := 0&nbsp; &nbsp; source := reflect.ValueOf(sour)&nbsp; &nbsp; // dist is expected to be a pointer, so use Elem() to&nbsp; &nbsp; // get the type of the value to which the pointer points&nbsp; &nbsp; target := reflect.ValueOf(dist).Elem()&nbsp; &nbsp; typeSource := reflect.TypeOf(sour)&nbsp; &nbsp; typeTarget := target.Type()&nbsp; &nbsp; for i := 0; i < source.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < target.NumField(); j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if typeSource.Field(i).Type == typeTarget.Field(j).Type && typeSource.Field(i).Name == typeTarget.Field(j).Name {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; counter = counter + 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; target.FieldByName(typeSource.Field(i).Name).Set(source.Field(i))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return uint(counter)}
随时随地看视频慕课网APP

相关分类

Go
我要回答