如何优雅地将一个数组的一部分复制到另一个数组中或注入到另一个数组中

时间:2018-12-06 08:00:11

标签: arrays go insert

我有以下有效的代码,但这里的要点是我想将任意长度的一个数组插入或插入另一个扩展其长度的静态大小的数组中:

package main

import (
    "fmt"
)

func main() {
    ffmpegArguments := []string{
        "-y",
        "-i", "invideo",
        // ffmpegAudioArguments...,
        "-c:v", "copy",
        "-strict", "experimental",
        "outvideo",
    }

    var outputArguments [12]string
    copy(outputArguments[0:3], ffmpegArguments[0:3])
    copy(outputArguments[3:7], []string{"-i", "inaudio", "-c:a", "aac"})
    copy(outputArguments[7:12], ffmpegArguments[3:8])

    fmt.Printf("%#v\n", ffmpegArguments)
    fmt.Printf("%#v\n", outputArguments)
}

https://play.golang.org/p/peQXkOpheK4

3 个答案:

答案 0 :(得分:3)

谈论优雅有点自以为是,但有人可能会想到KISS原则。顺便说一句,您可以对 slices 使用更简单的方法,它不需要您猜测输出数组的大小:

func inject(haystack, pile []string, at int) []string {
    result := haystack[:at]
    result = append(result, pile...)
    result = append(result, haystack[at:]...)

    return result
}

然后,按如下所示重写代码:

ffmpegArguments := []string{
    "-y",
    "-i", "invideo",
    "-c:v", "copy",
    "-strict", "experimental",
    "outvideo",
}

outputArguments := inject(ffmpegArguments, []string{"-i", "inaudio", "-c:a", "aac"}, 3)

fmt.Printf("%#v\n", ffmpegArguments)
fmt.Printf("%#v\n", outputArguments)

答案 1 :(得分:2)

由于您要附加到输出中,因此我建议这样做(简单且一致)并设置最大容量:

out := make([]string, 0, 12)
out = append(out, in[0:3]...)
out = append(out, []string{"-i", "inaudio", "-c:a", "aac"}...)
out = append(out, in[3:8]...)

请参阅:

package main

import (
    "fmt"
)

func main() {
    in := []string{
        "-y",
        "-i", "invideo",
        // ffmpegAudioArguments...,
        "-c:v", "copy",
        "-strict", "experimental",
        "outvideo",
    }

    out := make([]string, 0, 12)
    out = append(out, in[0:3]...)
    out = append(out, []string{"-i", "inaudio", "-c:a", "aac"}...)
    out = append(out, in[3:8]...)

    fmt.Println(in)
    fmt.Println(out)
}

结果:

[-y -i invideo -c:v copy -strict experimental outvideo]
[-y -i invideo -i inaudio -c:a aac -c:v copy -strict experimental outvideo]

答案 2 :(得分:0)

我最终通过首先对数组进行复制来修改@Alirus的答案,因为看起来第一个分配指向干草堆数组,随后的步骤修改了haystack切片:

// arrayInject is a helper function written by Alirus on StackOverflow in my
// inquiry to find a way to inject one array into another _elegantly_:
// https://stackoverflow.com/a/53647212/776896
func arrayInject(haystack, pile []string, at int) (result []string) {
	result = make([]string, len(haystack[:at]))
	copy(result, haystack[:at])
	result = append(result, pile...)
	result = append(result, haystack[at:]...)

	return result
}