douzhantanju1849 2016-08-13 16:02
浏览 463
已采纳

Golang动态变量参考

In Go, I would like to do something like this. I have a big object with many structs (using Google's protobuf). here is a contrived example:

person.name = "testing"
person.address.street = "123 test st"
person.address.city = "tester"
person.address.zip = 90210
person.billing.address.same = true

I would like to be able to dynamically reference things. for example:

key := "person.address.zip"
fmt.Println("the value of key: " + key) // would like to get 90210
key := "person.address.city"
fmt.Println("the value of key: " + key) // would like to get "tester"

Is this possible in Go? if so, how could I do that? essentially, I'm creating a report which only contains a subset of the object and I want to be able to create a mapping file where the user can map keys/values together and my program will output the value. I have this working in python, but wanted to try using Go :)

  • 写回答

2条回答 默认 最新

  • duandu6497 2016-08-14 03:42
    关注

    You may use func (v Value) FieldByName(name string) Value from reflect package:

    FieldByName returns the struct field with the given name. It returns the zero Value if no field was found. It panics if v's Kind is not struct.

    Like this working sample code:

    package main
    
    import "fmt"
    import "reflect"
    
    func main() {
        person := Person{}
        person.name = "testing"
        person.address.street = "123 test st"
        person.address.city = "tester"
        person.address.zip = 90210
        person.billing.address.same = true
    
        v := reflect.ValueOf(person)
        f := v.FieldByName("address")
        key := f.FieldByName("zip")
        fmt.Println(key)                   // 90210
        fmt.Println(f.FieldByName("city")) // tester    
    }
    
    type Person struct {
        name    string
        address Address
        billing Billing
    }
    type Billing struct {
        address Address
    }
    type Address struct {
        street, city string
        zip          int
        same         bool
    }
    

    output:

    90210
    tester
    

    And for your special case, you may use fmt.Println(field(person, "person.address.zip")), like this working sample code (just for demonstration):

    package main
    
    import "fmt"
    import "reflect"
    import "strings"
    
    func field(t interface{}, key string) reflect.Value {
        strs := strings.Split(key, ".")
        v := reflect.ValueOf(t)
        for _, s := range strs[1:] {
            v = v.FieldByName(s)
        }
        return v
    }
    func main() {
        person := Person{}
        person.name = "testing"
        person.address.street = "123 test st"
        person.address.city = "tester"
        person.address.zip = 90210
        person.billing.address.same = true
    
        fmt.Println(field(person, "person.address.zip"))  //90210
        fmt.Println(field(person, "person.address.city")) //tester
    }
    
    type Person struct {
        name    string
        address Address
        billing Billing
    }
    type Billing struct {
        address Address
    }
    type Address struct {
        street, city string
        zip          int
        same         bool
    }
    

    output:

    90210
    tester
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值