如何使用带有两个 []byte 切片或数组的 Go append? [英] How can I use Go append with two []byte slices or arrays?

查看:52
本文介绍了如何使用带有两个 []byte 切片或数组的 Go append?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

错误是:

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

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

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

http://code.google.com/p/go-wiki/维基/切片技巧

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

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

推荐答案

Go 编程语言规范

追加和复制切片

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

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是S的元素类型

将参数传递给 ... 参数

如果最后一个参数可以赋值给一个切片类型[]T,它可能是如果参数是后跟 ....

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 ....

<小时>

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

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

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

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

输出:

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

这篇关于如何使用带有两个 []byte 切片或数组的 Go append?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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