Convert strings, bytes and runes
Convert strings, bytes and runes
Use []byte(s) to obtain a mutable byte slice and string(b) to turn bytes back into a string. Use []rune(s) to decode a string to a slice of code points and string(rs) to encode runes. Choose byte conversion for binary data and rune conversion for code-point operations.
package main
import ( "fmt")
func main() { s := "Go" b := []byte(s) b[0] = 'N' fmt.Println(s, string(b))}Changing b does not modify s. Conversion has independent observable value semantics even if the compiler optimizes allocation.
Expected output:
Go NoReplace a complete rune
package main
import ( "fmt")
func main() { s := "Aé" r := []rune(s) r[1] = 'س' fmt.Println(s, string(r)) fmt.Println(string('A'))}Rune indexing changes a complete code point, not a byte. An integer-to-string conversion encodes a code point, not decimal digits; use fmt or strconv for number formatting. Decoding invalid UTF-8 to runes replaces invalid bytes with U+FFFD, so the round trip is not byte-preserving for invalid input.
Expected output:
Aé AسATry it locally
Convert "سلام" to runes, replace its first rune with م, and print the original and new string.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Strings and Unicode 06: Convert strings, bytes and runes
Check the lesson objective before moving on.
Which conversion decodes Unicode code points?
What does string of the integer value 65 produce?