[英]copy data from one golang slice struct to another slice strcut
Hi I have json data which I Unmarshal to machines
slice.您好,我有 json 数据,我将其解组到
machines
切片。 Now I am looking to copy/append each hostname
from machines
slice struct to service
Struct []hosts.现在我正在寻找从
machines
slice struct 复制/附加每个hostname
到service
Struct []hosts。 I have tried few methods but struggling to iterate over []hosts slice in service
struct.我尝试了几种方法,但努力迭代
service
结构中的 []hosts 切片。
Just wondering what is the best way to copy the value from one slice struct to another slice value inside some other struct.只是想知道将值从一个切片结构复制到其他结构内的另一个切片值的最佳方法是什么。
package main
import (
"encoding/json"
"fmt"
)
type Machine struct {
hostname string
Ip string
Name string
}
type Host struct {
HostName string `json:"host_name"`
Vars Var `json:"vars"`
}
type Service struct {
ServiceName string `json:"service_name"`
Required bool `json:"required"`
Hosts []Host `json:"hosts"`
Vars Var `json:"vars"`
}
func main() {
machineInfo := `[{"dns":"1.1.1.1.eu-south-1.compute.amazonaws.com","ip":"1.1.1.1","name":"Machine-1"},{"dns":"1.1.1.2.eu-south-1.compute.amazonaws.com","ip":"1.1.1.2","name":"Machine-2"}]`
var machines []Machine
var mService *Service
//convert the json to byts slice and then
json.Unmarshal([]byte(machineInfo), &machines)
//Data is now add to the structs
for i, _ := range machines {
mService.Hosts = append(mService.Hosts, machines[i].hostname)
}
fmt.Printf("Machines : %v", mService)
data, _ := json.Marshal(mService)
fmt.Println(string(data))
}
Let's take it from the top:让我们从头开始:
Export the hostname field by capitalizing it.通过大写导出主机名字段。 The JSON decoder ignores unexpected fields.
JSON 解码器忽略意外字段。 Also, add a tag so the field matches the document:
另外,添加一个标签,使字段与文档匹配:
type Machine struct {
Hostname string `json:"name"`
Ip string
Name string
}
Declare mServices as a value to avoid nil pointer panic:将 mServices 声明为一个值以避免 nil 指针恐慌:
var mService Service
Use a composite literal expression to create a host for append to the slice:使用复合文字表达式为切片创建 append 的主机:
mService.Hosts = append(mService.Hosts, Host{HostName: machines[i].Hostname})
https://go.dev/play/p/nTBVwM3l9Iw https://go.dev/play/p/nTBVwM3l9Iw
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.