Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!
Tips and Traps¶
string
is a primitive type in Golang, which means a string value has no methods on it but instead you have to use built-in functions (e.g.,len
) or functions in other modules (e.g., thestrings
module) to manipulate strings.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
len
returns the length of bytes of a string. It is not necessary the length of unicode characters. For example, callinglen
on 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`
s
Slicing of Strings¶
s := "how are you"
s
Each 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]
reflect.TypeOf(s[0])
s[:]
s[2:]
s[2:6]
strconv.Itoa(2)
strconv.Atoi("20")
Concatenate Strings¶
"how " + "are"
"how " + 2
"how " * 2
"how " + strconv.Itoa(2)
Concatenate/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)
strconv.Itoa(1)
Convert Strings to Integers¶
i, err := strconv.ParseInt("1", 10, 64)
i
The 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.