连接3个或更多切片的最简洁方法

问题描述 投票:-1回答:1

我正在寻找一种在Go中简洁有效地连接3个或更多切片的方法。

假设我要串联以下切片(所有代码都可以在这里找到https://play.golang.org/p/6682YiFF8qG:]

a := []int{1, 2, 3}
b := []int{4, 5, 6}
c := []int{7, 8, 9}

我的第一次尝试是通过使用append方法:

d1 := append(a, b...)
d1 = append(d1, c...) // [1 2 3 4 5 6 7 8 9]

但是,此方法很冗长,需要2个append调用才能串联三个切片。因此,对于n片,我将需要n-1调用来追加,这不仅冗长,而且效率低下,因为它需要多次分配。

我的下一个尝试是创建一个可变参数函数以仅使用一个新的切片分配来处理并置:

func concat(slicesOfSlices ...[]int) []int {
    var totalLengthOfSlices int

    for _, slice := range slicesOfSlices {
        totalLengthOfSlices += len(slice)
    }

    arr := make([]int, 0, totalLengthOfSlices)

    for _, slice := range slicesOfSlices {
        arr = append(arr, slice...)
    }

    return arr
}

然后我可以按以下方式使用它:

d2 := concat(a, b, c) // [1 2 3 4 5 6 7 8 9]

为了说明,我想在JavaScript中模拟散布运算符的以下便捷功能,我经常通过以下方式使用它:

const a = [1, 2, 3];
const b = [4, 5, 6];
const c = [7, 8, 9];

const d = [...a, ...b, ...c]; // [1, 2, 3, 4, 5, 6, 7, 8, 9]

换句话说,我正在寻找一种方法来执行类似d3 := append(a, b, c)d3 := append(a, b..., c...)的操作,但要使用标准的Go库或使用比我少的代码。

关于可能重复的注意事项

我不认为这是“如何串联两个切片”问题的重复,因为我的问题是关于以最简洁和惯用的方式串联3个或更多切片

我正在寻找一种在Go中简洁有效地连接3个或更多切片的方法。假设我要连接以下切片(所有代码都可以在此处找到-https://play.golang.org / ...

go append slice
1个回答
3
投票

您可以像这样使用第一种使用append的方法:

© www.soinside.com 2019 - 2024. All rights reserved.