如何从 golang 中的函数创建结构数组和 return?

How to make array of struct and return from a function in golang?

我最近开始使用 golang,我需要制作结构数组。下面是我的结构:

type Process struct {
    Key   string
    Value string
}

现在,根据我的方法,我需要 return []Process。下面是我的方法:

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

我对如何通过向其中添加单独的进程结构然后 return 来制作进程数组感到困惑。

使用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
}
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
}