ZBLOG

现在有一个结构体 A和一个结构体B,他们大部分的字段和tag 是相同的,那么该如何快速把相同字段的赋值,golang

在Go语言中,可以使用反射来实现相同字段的快速赋值。以下是一个示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "reflect"
  5. )
  6. type A struct {
  7. Field1 int `tag1:"value1"`
  8. Field2 string `tag2:"value2"`
  9. Field3 bool `tag3:"value3"`
  10. }
  11. type B struct {
  12. Field1 int `tag1:"newValue1"`
  13. Field2 string `tag2:"newValue2"`
  14. Field3 bool `tag3:"newValue3"`
  15. }
  16. func main() {
  17. a := A{
  18. Field1: 100,
  19. Field2: "hello",
  20. Field3: true,
  21. }
  22. b := B{}
  23. // 获取A和B的类型信息
  24. typeA := reflect.TypeOf(a)
  25. typeB := reflect.TypeOf(b)
  26. for i := 0; i < typeA.NumField(); i++ {
  27. fieldA := typeA.Field(i)
  28. fieldName := fieldA.Name
  29. if fieldB, ok := typeB.FieldByName(fieldName); ok {
  30. tagValue := fieldA.Tag.Get("json")
  31. valueA := reflect.ValueOf(a).FieldByName(fieldName).Interface()
  32. valueB := reflect.ValueOf(b).FieldByName(fieldName)
  33. valueB.Set(reflect.ValueOf(valueA))
  34. fmt.Printf("Assigned value %v to field %s with tag %s\n", valueB.Interface(), fieldName, tagValue)
  35. }
  36. }
  37. }

在上述代码中,通过反射获取结构体A和结构体B的类型信息。然后遍历结构体A的字段,并检查是否存在于结构体B中。如果存在,则获取对应字段的值并将其赋给结构体B。

注意,在这个示例中,我们使用了json标签作为示例。你可以根据实际情况更改相应的标签名称。

运行此代码将输出类似于以下内容:

  1. Assigned value 100 to field Field1 with tag json:"Field1"
  2. Assigned value hello to field Field2 with tag json:"Field2"
  3. Assigned value true to field Field3 with tag json:"Field3"

这样就完成了相同字段的快速赋值操作。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=16191

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?