简体   繁体   中英

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

{
   "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. 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):

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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