dsfs64664 2011-12-11 02:13
浏览 628
已采纳

如何使用带有两个[] byte切片或数组的Go append?

I recently tried appending two byte array slices in Go and came across some odd errors. My code is:

one:=make([]byte, 2)
two:=make([]byte, 2)
one[0]=0x00
one[1]=0x01
two[0]=0x02
two[1]=0x03

log.Printf("%X", append(one[:], two[:]))

three:=[]byte{0, 1}
four:=[]byte{2, 3}

five:=append(three, four)

And the errors are:

cannot use four (type []uint8) as type uint8 in append
cannot use two[:] (type []uint8) as type uint8 in append

Which taken into consideration the alleged robustness of Go's slices shouldn't be a problem:

http://code.google.com/p/go-wiki/wiki/SliceTricks

What am I doing wrong, and how should I go about appending two byte arrays?

  • 写回答

2条回答 默认 最新

  • dougao2830 2011-12-11 02:55
    关注

    The Go Programming Language Specification

    Appending to and copying slices

    The variadic function append appends zero or more values x to s of type S, which must be a slice type, and returns the resulting slice, also of type S. The values x are passed to a parameter of type ...T where T is the element type of S and the respective parameter passing rules apply.

    append(s S, x ...T) S // T is the element type of S

    Passing arguments to ... parameters

    If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by ....


    You need to use []T... for the final argument.

    For your example, with the final argument slice type []byte, the argument is followed by ...,

    package main
    
    import "fmt"
    
    func main() {
        one := make([]byte, 2)
        two := make([]byte, 2)
        one[0] = 0x00
        one[1] = 0x01
        two[0] = 0x02
        two[1] = 0x03
        fmt.Println(append(one[:], two[:]...))
    
        three := []byte{0, 1}
        four := []byte{2, 3}
        five := append(three, four...)
        fmt.Println(five)
    }
    

    Playground: https://play.golang.org/p/2jjXDc8_SWT

    Output:

    [0 1 2 3]
    [0 1 2 3]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿