尝试使用可变参数组合多个切片, 我收到错误消息:无法使用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)
答案 0 :(得分:1)
您的可变参数调用参数格式很好。
该错误是由于您的函数Combine
返回了一项而不是两项:
// actual, _ := Combine(test.s1, test.s2) // fails as only one item is returned
actual := Combine(test.s1, test.s2)