登录
首页 >  Golang >  Go问答

如何给reflect Field()赋值?

来源:stackoverflow

时间:2024-03-30 20:45:25 207浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《如何给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)
    }
}

解决方案


要使 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)
}

本篇关于《如何给reflect Field()赋值?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>