Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I append string to byte slice as the Go reference specified?

Tags:

string

slice

go

Quote from the reference of append of Go

As a special case, it is legal to append a string to a byte slice, like this:
slice = append([]byte("hello "), "world"...)

But I find I can't do that as this snippet:

package main
import "fmt"

func main(){
    a := []byte("hello")
    s := "world"
    a = append(a, s) //*Error*: can't use s(type string) as type byte in append 
    fmt.Printf("%s",a)
}

What have I done wrong?

like image 459
armnotstrong Avatar asked Jan 14 '15 04:01

armnotstrong


People also ask

How do I append in Slice?

As we already know that slice is dynamic, so the new element can be appended to a slice with the help of append() function. This function appends the new element at the end of the slice. Here, this function takes s slice and x… T means this function takes a variable number of arguments for the x parameter.

How do you concatenate bytes in Go?

In the Go slice of bytes, you are allowed to join the elements of the byte slice with the help of Join() function. Or in other words, Join function is used to concatenate the elements of the slice and return a new slice of bytes which contain all these joined elements separated by the given separator.

How do I append in Golang?

Since slices are dynamically-sized, you can append elements to a slice using Golang's built-in append method. The first parameter is the slice itself, while the next parameter(s) can be either one or more of the values to be appended.

What is a byte slice in Go?

Byte slices are a list of bytes that represent UTF-8 encodings of Unicode code points. Taking the information from above, we could create a byte slice that represents the word “Go”: bs := []byte{71, 111} fmt.Printf("%s", bs) // Output: Go. You may notice the %s used here. This converts the byte slice to a string.


1 Answers

You need to use "..." as suffix in order to append a slice to another slice. Like this:

package main import "fmt"  func main(){     a := []byte("hello")     s := "world"     a = append(a, s...) // use "..." as suffice      fmt.Printf("%s",a) } 

You could try it here: http://play.golang.org/p/y_v5To1kiD

like image 136
Andy Xu Avatar answered Nov 11 '22 12:11

Andy Xu