可变参数切片作为参数错误:无法初始化具有1个值的2个变量

时间:2019-04-11 22:31:21

标签: go

尝试使用可变参数组合多个切片, 我收到错误消息:无法使用1个值初始化2个变量

如何调用此Combine函数?

代码如下:

func Combine(ss ...[]string) []string {
    mp := map[string]bool{}

    for _, s := range ss {
        for _, v := range s {
            if v != "" {
                if _, ok := mp[v]; !ok {
                    mp[v] = true
                }
            }
        }
    }

    combined := []string{}

    for v := range mp {
        combined = append(combined, v)
    }

    return combined
}



tests := []struct {
        caseName string
        s1       []string
        s2       []string
        want     []string
    }{
        {
            caseName: "Test combining 2 slices",
            s1:       []string{"a", "b", "c", "c", ""},
            s2:       []string{"a", "b", "z", "z", "", "y"},
            want:     []string{"a", "b", "c", "y", "z"},
        },
    }


actual, _ := Combine(test.s1, test.s2)

1 个答案:

答案 0 :(得分:1)

您的可变参数调用参数格式很好。

该错误是由于您的函数Combine返回了一项而不是两项:

// actual, _ := Combine(test.s1, test.s2) // fails as only one item is returned

actual := Combine(test.s1, test.s2)