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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With