[英]How to set the value of a field of type time.Time as time.Now() using reflect in Golang
[英]How to set array value to a field in golang using reflect?
我有一個具有以下字段的結構
type Config struct {
Address[]string
Name string
}
我正在從JSON格式的文件中讀取此配置的值
{
"Address": ["xx.xx.xx.xx","xx.xx.xx.xx"],
"Name":"Name"
}
我已經使用Reflect來識別類型並將其值設置為Config。我能夠使用func(v Value)SetString(x string)來設置Name字段的值,這是反射中的一種內置方法。 有沒有一種方法可以直接將[]字符串值設置為字段? 請幫忙。
您可以為此使用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.