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

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


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


三国纷争
浏览 143回答 3
3回答

慕容708150

讲优雅有些自以为是,但可以提出KISS原则。顺便说一句,您可以对切片使用更简单的方法,不需要您猜测输出数组的大小: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)

慕虎7371278

由于您要附加到输出,我建议这样做(简单且一致)并设置最大容量: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 mainimport (    "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]

HUX布斯

看起来第一个赋值指向 haystack 数组,随后的步骤修改了切片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_: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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go