V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
jonathanchoo
V2EX  ›  Go 编程语言

请教 Go 用反射修改结构体的值的问题

  •  
  •   jonathanchoo · 2021-01-14 16:53:21 +08:00 · 1388 次点击
    这是一个创建于 1195 天前的主题,其中的信息可能已经有所发展或是发生改变。

    如果是普通的结构体,遍历 numField 根据 Field(i).Name 修改就可以了

    但是如果遇到嵌套结构体怎么办

    例如

    type A struct {
      field1 string
      ...
      B
    }
    
    type B struct {
      field2 string
    }
    

    如何修改修改 field2 的值呢?

    2 条回复    2021-01-14 17:42:26 +08:00
    notamail
        1
    notamail  
       2021-01-14 17:35:02 +08:00
    1. 你这并不是嵌套结构体。。。
    2. 这种结构可以考虑用 map 来处理
    joesonw
        2
    joesonw  
       2021-01-14 17:42:26 +08:00
    1. 私有变量改不了的.
    2. struct 也是修改不了, 要 *B


    type A struct {
    Field1 string
    *B
    }

    type B struct {
    Field2 string
    }

    func main() {
    a := A{B: &B{Field2: "123"}}
    println(a.B.Field2)
    v := reflect.ValueOf(&a)
    v.Elem().FieldByName("B").Elem().FieldByName("Field2").Set(reflect.ValueOf("456"))
    println(a.B.Field2)
    }



    https://play.golang.org/p/dJ5sWunyVby
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1054 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:30 · PVG 06:30 · LAX 15:30 · JFK 18:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.