简体   繁体   English

如何使用反射将数组值设置为golang中的字段?

[英]How to set array value to a field in golang using reflect?

I have a Struct with following fields 我有一个具有以下字段的结构

type Config struct {
        Address[]string
        Name string
}

I am reading the values for this Config from a file in JSON format 我正在从JSON格式的文件中读取此配置的值

{
   "Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
   "Name":"Name"
}

I have used Reflect to identify the type and set its value to Config.I am able to set the value of Name field using func (v Value) SetString(x string) which is an inbuilt method in reflect. 我已经使用Reflect来识别类型并将其值设置为Config。我能够使用func(v Value)SetString(x string)来设置Name字段的值,这是反射中的一种内置方法。 Is there a way to set []string values directly to a field? 有没有一种方法可以直接将[]字符串值设置为字段? Please help. 请帮忙。

You can use the json package for that (it uses reflect internally): 您可以为此使用json包(它在内部使用反射):

package main

import (
    "encoding/json"
    "fmt"
)

type Config struct {
    Address []string
    Name    string
}

var someJson = []byte(`{
   "Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
   "Name":"Name"
}`)

func main() {
    var config Config
    err := json.Unmarshal(someJson, &config)
    if err != nil {
        fmt.Println("error: ", err)
    }
    fmt.Printf("%v", config)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM