【问题标题】:How can I use Go append with two []byte slices or arrays?如何使用带有两个 []byte 切片或数组的 Go append?
【发布时间】:2012-01-17 16:31:04
【问题描述】:

我最近尝试在 Go 中附加两个字节数组切片,但遇到了一些奇怪的错误。我的代码是:

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)

错误是:

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

考虑到所谓的 Go 切片的健壮性应该不是问题:

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

我做错了什么,我应该如何追加两个字节数组?

【问题讨论】:

    标签: arrays append byte go


    【解决方案1】:

    The Go Programming Language Specification

    Appending to and copying slices

    可变参数函数append将零个或多个值x附加到s 输入S,必须是切片类型,并返回结果切片, 也是S 类型。值x 被传递给...T 类型的参数 其中TS 的元素类型和相应的参数传递 规则适用。

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

    Passing arguments to ... parameters

    如果最后一个参数可分配给切片类型[]T,它可能是 如果参数是 ...T 参数的值 其次是...


    您需要使用[]T... 作为最后一个参数。

    对于您的示例,最终参数切片类型为[]byte,参数后跟...

    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)
    }
    

    游乐场:https://play.golang.org/p/2jjXDc8_SWT

    输出:

    [0 1 2 3]
    [0 1 2 3]
    

    【讨论】:

      【解决方案2】:

      append() 获取一个[]T 类型的切片,然后是切片成员T 类型的可变数量的值。换句话说,如果您将[]uint8 作为切片传递给append(),那么它希望每个后续参数都是uint8

      解决方案是使用slice... 语法来传递切片来代替可变参数参数。你的代码应该是这样的

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

      five:=append(three, four...)
      

      【讨论】:

        猜你喜欢
        • 2012-11-10
        • 2017-03-12
        • 1970-01-01
        • 2013-04-21
        • 2015-11-11
        • 2012-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多