go - 拆包 slice 时 slice

标签 go

我有以下代码

func Sum(a []int) int {
    res := 0
    for _, n := range a {
        res += n
    }
    return res
}

func SumAll(ns ...[]int) (sums []int) {
    for _, s := range ns {
        sums = append(sums, Sum(s))
    }
    return
}

//SumAllTails sums [:1] in each slice
func SumAllTails(sls ...[]int) []int {
    newsls := [][]int{}
    for _, sl := range sls {
        newsls = append(newsls, sl[1:])
    }
    return SumAll(newsls...)
}

理想情况下,我想将最后一个函数更改为这样的

func SumAllTails(sls ...[]int) []int {
    return SumAll(sls[:][1:]...)
}

最后一位返回除第一个之外的每个 slice ,但我想做的是从位置 1 开始解包每个 slice ,省略 0 处的值。有没有办法在 go 中实现此目的?

最佳答案

我认为在不先遍历 slice 的情况下做你想做的事情的唯一方法是编写一个 SumAlln 函数:

func SumAlln(n int, ns ...[]int) (sums []int) {
    for _, s := range ns {
        sums = append(sums, Sum(s[n:]))
    }
    return
}

func SumAll(ns...[]int) []int {
    return SumAlln(0,ns...)
}

然后调用SumAlln

关于go - 拆包 slice 时 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57925888/

相关文章:

go - 可以在一个 FlatBuffers 缓冲区中编码多个表吗?

json - 一个字段的Golang多个json标签名称

sockets - 使用 golang 从连接到网络接口(interface)的原始套接字读取

windows - 系统调用 - 如何在 Go 中使用 LPWSTR?

go - 在 Go 中具有非标准字段的结构数组上的 MarshalJSON

go - channel 和 WaitGroup 进入死锁

go - 使用 goroutines 处理并发的 neo4j 连接

go - 如何通过反射在GO中获取结构字段的地址

sql - 获取指向结构字段值的指针

go - 在 Golang 中使用 BigQuery Write API