我如何使用转到追加了两个[]字节的片或数组? [英] How can I use Go append with two []byte slices or arrays?
问题描述
我最近尝试在追加走二字节数组切片并在一些奇怪的错误来了。我的code是:
之一:化妆=([]字节,2)
二:=令([]字节,2)
酮[0] = 0×00
[1] = 0×01
2个[0] = 0×02
有2个[1] = 0×03log.Printf(%X追加(一个[:],二[:]))三:= []字节{0,1}
四:= []字节{2,3}五:=追加(三,四)
和的错误是:
不能使用四(键入[] UINT8)作为追加型UINT8
不能同时采用两种[:](键入[] UINT8)作为追加型UINT8
其中考虑到涉嫌Go的切片的鲁棒性不应该是一个问题:
<一个href=\"http://$c$c.google.com/p/go-wiki/wiki/SliceTricks\">http://$c$c.google.com/p/go-wiki/wiki/SliceTricks
我在做什么错了,我应该如何去追加两个字节数组?
的可变参数函数
追加
追加零个或多个值X
到取值
的
键入取值
,它必须是一个切片类型,并返回结果切片,
同样类型的取值
。值X
传递给类型的参数...牛逼
其中,T
是取值
的元素类型和各自的参数传递
规则适用。
追加(S S,X ...牛逼)S // T是S的元素类型
如果最后一个参数被分配给一个片类型
[] T ...
,它可能是
通过不变的...牛逼
参数的值如果该参数
其次是...
。
块引用>您需要使用
[] T ... ...
的最后一个参数。例如,
主包进口FMTFUNC的main(){
之一:化妆=([]字节,2)
二:=令([]字节,2)
酮[0] = 0×00
[1] = 0×01
2个[0] = 0×02
有2个[1] = 0×03
fmt.Println(追加(一个[:],2个[:] ...))
三:= []字节{0,1}
四:= []字节{2,3}
五:=追加(三,四......)
fmt.Println(五)个
}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?
解决方案Appending to and copying slices
The variadic function
append
appends zero or more valuesx
tos
of typeS
, which must be a slice type, and returns the resulting slice, also of typeS
. The valuesx
are passed to a parameter of type...T
whereT
is the element type ofS
and the respective parameter passing rules apply.
append(s S, x ...T) S // T is the element type of S
Passing arguments to
...
parametersIf 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 example,
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) }
这篇关于我如何使用转到追加了两个[]字节的片或数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!