No livestream today, as I’m traveling with my family. See you next week!
Conversions to and from a string type
…
- Converting a value of a string type to a slice of bytes type yields a non-nil slice whose successive elements are the bytes of the string.
[]byte("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} []byte("") // []byte{} bytes("hellø") // []byte{'h', 'e', 'l', 'l', '\xc3', '\xb8'} []myByte("world!") // []myByte{'w', 'o', 'r', 'l', 'd', '!'} []myByte(myString("🌏")) // []myByte{'\xf0', '\x9f', '\x8c', '\x8f'}
- Converting a value of a string type to a slice of runes type yields a slice containing the individual Unicode code points of the string.
[]rune(myString("白鵬翔")) // []rune{0x767d, 0x9d6c, 0x7fd4} []rune("") // []rune{} runes("白鵬翔") // []rune{0x767d, 0x9d6c, 0x7fd4} []myRune("♫♬") // []myRune{0x266b, 0x266c} []myRune(myString("🌐")) // []myRune{0x1f310}
There should be no surprises here, as these are just the inverse of the previous two rules. The only exception here is that while you can convert from a nil byte slice or rune slice to a empty string, there is no way to convert from a string to an nil byte or rune slice.
Tomorrow we’ll over the last rule regarding string conversions.
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)