Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

Tips and Traps

  1. In Golang, a string is implemented as a struct containing a data pointer (pointing to a read-only slice of bytes) and a length.

  2. Raw string literals, delimited by backticks (back quotes), are interpreted literally. They can contain line breaks, and backslashes have no special meaning.

  3. The built-in function len returns the length of bytes of a string. It is not necessary the length of unicode characters. For example, calling len 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
this is a multiline string

Slicing of Strings

s := "how are you"
s
how are you

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]
104
reflect.TypeOf(s[0])
uint8
s[:]
how are you
s[2:]
w are you
s[2:6]
w ar
strconv.Itoa(2)
2
strconv.Atoi("20")
20 <nil>

Concatenate Strings

"how " + "are"
how are
"how " + 2
how how
"how " * 2
invalid binary operation "how " * 2
"how " + strconv.Itoa(2)
how 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)
1
strconv.Itoa(1)
1

Convert Strings to Integers

i, err := strconv.ParseInt("1", 10, 64)
i
1

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.