Home > Software design >  How to make array of struct and return from a function in golang?
How to make array of struct and return from a function in golang?

Time:01-20

I recently started working with golang and I need to make array of struct. Below is my struct:

type Process struct {
    Key   string
    Value string
}

Now from my method I need to return []Process. Below is my method:

func procData(values []string) ([]Process, error) {
    var process Process
    for _, value := range values {
        pieces := strings.Split(value, "-")
        if len(pieces) > 1 {
            process = Process{pieces[0], pieces[1]}
        } else if len(pieces) > 2 {
            process = Process{pieces[0], pieces[2]}
        }
        // add process struct process array? how to add process struct to make Process array
    }
}

I am confuse on how to make Process array by adding individual process struct into them and then return it.

CodePudding user response:

Use append to collect the results in a slice.

func procData(values []string) ([]Process, error) {
    var result []Process
    for _, value := range values {
        var process Process
        pieces := strings.Split(value, "-")
        if len(pieces) > 1 {
            process = Process{pieces[0], pieces[1]}
        } else if len(pieces) > 2 {
            process = Process{pieces[0], pieces[2]}
        }
        result = append(result, process)
    }
    return result
}

CodePudding user response:

func procData(values []string) ([]Process, error) {
    processList := make([]Process, len(values))
    var process Process
    for _, value := range values {
        pieces := strings.Split(value, "-")
        if len(pieces) > 1 {
            process = Process{pieces[0], pieces[1]}
        } else if len(pieces) > 2 {
            process = Process{pieces[0], pieces[2]}
        }
        // add process struct process array? how to add process struct to make Process array
        processList = append(processList, process)
    }
    return processList
}
  •  Tags:  
  • Related