为了账号安全,请及时绑定邮箱和手机立即绑定

将数据从一个 golang 切片结构复制到另一个切片 strcut

将数据从一个 golang 切片结构复制到另一个切片 strcut

Go
噜噜哒 2022-11-15 09:51:24
您好,我有 json 数据,我将其解组为machines 切片。现在我正在寻找将每个hostname从 machinesslice struct 复制/附加到serviceStruct []hosts 。我尝试了几种方法,但努力迭代servicestruct 中的 []hosts 切片。只是想知道将值从一个切片结构复制到另一个结构内的另一个切片值的最佳方法是什么。package mainimport (    "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))}
查看完整描述

1 回答

?
绝地无双

TA贡献1946条经验 获得超4个赞

让我们从顶部开始:


通过大写导出主机名字段。JSON 解码器忽略意外字段。另外,添加一个标签,使字段与文档匹配:


type Machine struct {

    Hostname string `json:"name"`

    Ip       string

    Name     string

}

将 mServices 声明为一个值以避免 nil 指针恐慌:


var mService Service

使用复合文字表达式创建主机以附加到切片:


    mService.Hosts = append(mService.Hosts, Host{HostName: machines[i].Hostname})

https://go.dev/play/p/nTBVwM3l9Iw


查看完整回答
反对 回复 2022-11-15
  • 1 回答
  • 0 关注
  • 91 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信