This one-liner assigns a string to a slice of bytes:

package main

func main() {

    var s string

    //...

    b := []byte(s)

    //...
}

I found this useful when using ioutil.WriteFile, which accepts a bytes slice as its data parameter:

WriteFile func(filename string, data []byte, perm os.FileMode) error

e.g.:

ioutil.WriteFile(filePath, []byte(content), 0755)

Pssst! Also check my latest YouTube video



I am writing a book on how to create a successful blog as a developer.
It will be released late February.
Signup to my newsletter to get 2/3 free chapters in your inbox in the next few weeks!