Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

How can I use Go append with two []byte slices or arrays?

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?

question from:https://stackoverflow.com/questions/8461462/how-can-i-use-go-append-with-two-byte-slices-or-arrays

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The Go Programming Language Specification

Appending to and copying slices

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 is the element type of S

Passing arguments to ... parameters

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


You need to use []T... for the final argument.

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

Playground: https://play.golang.org/p/2jjXDc8_SWT

Output:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...