Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何将Go append与两个[]字节片或数组一起使用?_Arrays_Append_Byte_Go - Fatal编程技术网

Arrays 如何将Go append与两个[]字节片或数组一起使用?

Arrays 如何将Go append与两个[]字节片或数组一起使用?,arrays,append,byte,go,Arrays,Append,Byte,Go,我最近尝试在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

我最近尝试在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切片的所谓健壮性,这不应该是一个问题:

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

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

解决方法是使用
slice…
语法传递一个slice来代替varargs参数。您的代码应该如下所示

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

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

append(s,x…T)s//T是s的元素类型

如果最后一个参数可分配给切片类型
[]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)
}
游乐场:

输出:

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