Go中的地道切片拼接? [英] Idiomatic slice splice in Go?

查看:158
本文介绍了Go中的地道切片拼接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码来实现拼接(也就是说,给定一个字节片满,另一个字节片部分,以及一个表示完整位置的int值,我想用部分覆盖):

 包主
$ b导入(
fmt
字节


func main(){
full:= [] byte {0,0,0,0,0,0,0}
part:= [] byte {1 ,1,1}

newFull1:= splice(full,part,2)
fmt.Println(newFull1)
// [0 0 1 1 1 0 0]

newFull2:= splice(full,part,3)
fmt.Println(newFull2)
// [0 0 0 1 1 1 0]
}

func splice(full [] byte,part [] byte,pos int)[] byte {
return bytes.Join([] [] byte {full [:pos],part,full [len(full [:pos])+ len(part):]},[] byte {})
}

基本上,我的方法会连接3个字节的切片:完整的第一部分不会被部分,全部部分和全部剩余部分覆盖。有没有更好的/更习惯的方式来做到这一点?我无法找到在标准库中实现此方法。



  func main(){
full:= [] byte {0,0,0,0,0,0,0}
部分:= []字节{1,1,1}

拷贝(全部[2:],部分)
fmt.Println(full)
}

playground



尽管这样会覆盖全部。如果您想保留原件,可以先使用append函数创建一个副本。

  func main(){
full:= [] byte {0,0,0,0,0,0}
part:= [] byte {1,1,1}

newFull: = append([] byte {},full ...)
copy(newFull [2:],part)
fmt.Println(newFull:,newFull)
fmt.Println (full full:,full)
}

playground

请注意,这仍然有您的原始代码的限制,部分必须符合完整范围。

I have the following code for implementing a splice (that is, given a byte slice full, another byte slice part, and an int pos representing the position in full that I want to overwrite with part):

package main

import (
    "fmt"
    "bytes"
)

func main() {
    full := []byte{0,0,0,0,0,0,0}
    part := []byte{1,1,1}

    newFull1 := splice(full, part, 2)
    fmt.Println(newFull1)
    // [0 0 1 1 1 0 0]

    newFull2 := splice(full, part, 3)
    fmt.Println(newFull2)
    // [0 0 0 1 1 1 0]
}

func splice(full []byte, part []byte, pos int) []byte {
    return bytes.Join([][]byte{full[:pos], part, full[len(full[:pos])+len(part):]}, []byte{})
}

Basically, my method does a join of 3 byte slices: the first part of full that doesn't get overwritten by part, all of part, and then the remaining part of full. Is there a better/more idiomatic way of doing this? I wasn't able to find a method that implemented this in the standard library.

解决方案

If you know part is completely within the bounds of full, you can use the copy function.

func main() {
    full := []byte{0, 0, 0, 0, 0, 0, 0}
    part := []byte{1, 1, 1}

    copy(full[2:], part)
    fmt.Println(full)
}

playground

That overwrites full though. If you wanted to preserve the original, you could make a copy first with the append function.

func main() {
    full := []byte{0, 0, 0, 0, 0, 0, 0}
    part := []byte{1, 1, 1}

    newFull := append([]byte{}, full...)
    copy(newFull[2:], part)
    fmt.Println("newFull:      ", newFull)
    fmt.Println("original full:", full)
}

playground

Note that this still has the limitation of your original code that part must fit within the bounds of full.

这篇关于Go中的地道切片拼接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆