Golang: String

By Xah Lee. Date: . Last updated: .

Intepreted String Literal

String syntax is like this:


package main

import "fmt"

func main() {

	var x = "abc and ♥"

	// abc and ♥

String can contain Unicode character, example: (U+2665: BLACK HEART SUIT)

Any character can appear between the "double quotes", except the quote itself or newline character.

To include newline, use \n.

To include a quote character, use \", example: "the \"thing\""

Backslash Escapes

Golang: String Backslash Escape

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 is a Sequence of Bytes

For example, character A has codepoint 65 in decimal , and 41 in hexadecimal. So, "A" and "\x41" creates the same string.

package main

import "fmt"

func main() {

	fmt.Printf("%v\n", "A" == "\x41") // true


String Index

Returns the nth byte of string s.
Index start at 0.
The return value's type is byte. [see Golang: Basic Types]
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


String Functions

Golang: String Functions

Print String: Bytes vs Characters

Golang: Print String


Before you can work with string as character (instead of byte) sequence, you need to understand rune.

Golang: Rune

Working with String as Character Sequence

Golang: String, Byte Slice, Rune Slice