Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
In Golang, a string is implemented as a struct containing a data pointer (pointing to a read-only slice of bytes) and a length.
Raw string literals, delimited by backticks (back quotes), are interpreted literally. They can contain line breaks, and backslashes have no special meaning.
The built-in function
lenreturns the length of bytes of a string. It is not necessary the length of unicode characters. For example, callinglenon a Chinese character returns 3 instead of 1.
import "strings"
import "fmt"
import "strconv"
import "reflect"Backtick / Multi-line Strings¶
s := `this is
a multiline
string`
sthis is
a multiline
stringSlicing of Strings¶
s := "how are you"
show are youEach element of a string is a unsigned 8-bit integer (since Golang uses the UTF-8 encoding for strings). Notice it might or might not correspond to a character in the original string since an UTF-8 character might use up to 4 bytes.
s[0]104reflect.TypeOf(s[0])uint8s[:]how are yous[2:]w are yous[2:6]w arstrconv.Itoa(2)2strconv.Atoi("20")20 <nil>Concatenate Strings¶
"how " + "are"how are"how " + 2how how "how " * 2invalid binary operation "how " * 2"how " + strconv.Itoa(2)how 2Concatenate/Join an Array of Strings¶
Please refer to
Manipulate Strings Using the strings Module in Golang
for more discussions.
Comparing Strings¶
Convert Integers to Strings¶
import "fmt"
import "strconv"fmt.Sprintf("%d", 1)1strconv.Itoa(1)1Convert Strings to Integers¶
i, err := strconv.ParseInt("1", 10, 64)
i1The strings Module¶
Please refer to
Manipulate Strings Using the strings Module in Golang
for detailed discussions.
Format Strings¶
Please refer to Format Strings in Golang for detailed discussions.
Strings in Golang Are UTF-8¶
Please refer to Strings in Golang Are UTF-8 for detailed discussions.