Golang: String
Golang: What is String
String Syntax (Intepreted String Literal)
String syntax is like this:
"abc"
package main import "fmt" func main() { var x = "abc and ♥" fmt.Println(x) // abc and ♥ }
String can contain Unicode character, e.g. ♥ (U+2665: BLACK HEART SUIT)
Any character can appear between QUOTATION MARK, except the QUOTATION MARK itself or newline character.
To include newline, use \n.
To include a QUOTATION MARK, use \", e.g. "the \"thing\""
Backslash Escapes
Raw String Literal
If you don't want backslash to have special meaning, use ` (U+60: GRAVE ACCENT) to quote the string.
var x = `long text`
Anything can appear inside except the grave accent char itself.
And, carriage return character (Unicode codepoint 13) in it is discarded.
If you run the command line tool gofmt, it will remove carriage return.
package main import "fmt" var x = `long text many lines tab too` func main() { fmt.Printf("%v\n", x) }
String Index
s[n]-
- Returns the nth byte of string s.
- Index start at 0.
- The return value's type is
byte. 〔see Golang: Basic Types〕
If the string contains ASCII Characters only, then index corresponds to characters.
If the string contains non-ASCII characters, index does not corresponds to characters.
💡 TIP: If you want to work with string as characters not bytes, you need to convert it to rune slice. See Golang: String, Byte Slice, Rune Slice
package main import "fmt" func main() { var x = "abc" fmt.Printf("%#v\n", x[0]) // 0x61 fmt.Printf("%#v\n", x[1]) // 0x62 fmt.Printf("%#v\n", x[2]) // 0x63 }