Home > Back-end >  copy data from one golang slice struct to another slice strcut
copy data from one golang slice struct to another slice strcut

Time:03-01

Hi I have json data which I Unmarshal tomachines slice . Now I am looking to copy/append each hostname from machines slice struct to service Struct []hosts . I have tried few methods but struggling to iterate over []hosts slice in service struct .

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

CodePudding user response:

Let's take it from the top:

Export the hostname field by capitalizing it. The JSON decoder ignores unexpected fields. 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:

var mService Service

Use a composite literal expression to create a host for append to the slice:

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

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

  •  Tags:  
  • go
  • Related