The*_*chu 27 arrays byte append 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)
Run Code Online (Sandbox Code Playgroud)
错误是:
cannot use four (type []uint8) as type uint8 in append
cannot use two[:] (type []uint8) as type uint8 in append
Run Code Online (Sandbox Code Playgroud)
考虑到Go的切片所谓的稳健性应该不是问题:
http://code.google.com/p/go-wiki/wiki/SliceTricks
我做错了什么,我应该如何添加两个字节数组呢?
pet*_*rSO 43
可变参数函数向类型
append附加零个或多个值,该值必须是切片类型,并返回结果切片,也是类型.这些值将传递给type的参数, 其中元素类型为,并且相应的参数传递规则适用.xsSSx...TTS
append(s S, x ...T) S // T is the element type of S如果最终参数可分配给切片类型
[]T,则可以将其作为...T参数的值(如果参数后跟参数)保持不变....
您需要使用[]T...最终参数.
例如,
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)
}
Run Code Online (Sandbox Code Playgroud)
append()采用切片类型[]T,然后采用切片成员类型的可变数量的值T.换句话说,如果您将a []uint8作为切片传递给append()那么它希望每个后续参数都是a uint8.
对此的解决方案是使用slice...语法来传递切片来代替varargs参数.你的代码应该是这样的
log.Printf("%X", append(one[:], two[:]...))
Run Code Online (Sandbox Code Playgroud)
和
five:=append(three, four...)
Run Code Online (Sandbox Code Playgroud)