Golang: What is String
What is String
String is a datatype that represent sequence of characters. However, different programing languages implement them in different ways. Understanding this is critical for mastering the language, because string is one of the most used datatype.
In golang, a string is technically a sequence of bytes.
If you are beginner, you can skip this section.
String is a Sequence of Bytes
- Golang string is a sequence of Bytes.
- Each character in string is converted to bytes. If the character is ASCII Character, then it is 1 byte. But if it is non-ASCII char, it is 1 to 4 bytes by UTF-8 encoding. 〔see Unicode Basics: Character Set, Encoding, UTF-8〕
- Go string can contain any Unicode character, but stored as bytes.
- String can store any byte sequence, and can contain byte sequences that is not valid encoding of any character. You can create a string of any byte by using the hexadecimal escape
\xhh
. 〔see Golang: String Backslash Escape〕
package main import "fmt" // character A has codepoint 65 in decimal , and 41 in hexadecimal. So, "A" and "\x41" create the same string. func main() { fmt.Printf("%v\n", "A" == "\x41") // true }
package main import "fmt" // showing how string is byte sequence, not char sequence func main() { // string of a single char var x = "♥" // name: BLACK HEART SUIT // codepoint 9829, hexadecimal 2665 // utf8 encoding: E2 99 A5 // length fmt.Printf("%v\n", len(x)) // 3 // first byte in hexadecimal fmt.Printf("%x\n", x[0]) // e2 }