How to Convert String to Bytes in Go
Created
Modified
Using byte Function
The easiest way to convert string to []byte in Golang:
package main
import "fmt"
func main() {
s := "Hello"
b := []byte(s)
fmt.Printf("%v\n", b)
}
[72 101 108 108 111]
Using copy Function
The copy built-in function copies elements from a source slice into a destination slice.
You can use copy function to assign string to bytes. The following example:
package main
import "fmt"
func main() {
s := "Hello"
b := [3]byte{}
copy(b[:], s)
fmt.Printf("%v\n", b)
c := [7]byte{}
copy(c[:], s)
fmt.Printf("%v\n", c)
}
[72 101 108] [72 101 108 108 111 0 0]
If the string is too long, copy will only copy the part of the string that fits (and multi-byte runes may then be copied only partly, which will corrupt the last rune of the resulting string).