The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
jonathanchoo

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

  •  
  •   jonathanchoo · Jan 14, 2021 · 1998 views
    This topic created in 1954 days ago, the information mentioned may be changed or developed.

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

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

    例如

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

    如何修改修改 field2 的值呢?

    2 replies    2021-01-14 17:42:26 +08:00
    notamail
        1
    notamail  
       Jan 14, 2021
    1. 你这并不是嵌套结构体。。。
    2. 这种结构可以考虑用 map 来处理
    joesonw
        2
    joesonw  
       Jan 14, 2021
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2757 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 57ms · UTC 12:53 · PVG 20:53 · LAX 05:53 · JFK 08:53
    ♥ Do have faith in what you're doing.