How to Use Strings in Golang

Created
Modified

What is a String?

A string is an immutable sequence of bytes. Strings may contain arbitrary data, including bytes with value 0, but usually they contain human-readable text.

Make a main.go file containing the following:

package main

import "fmt"

func main() {

  s := "Hello, 世界"
  fmt.Println(len(s))     // "13"
  fmt.Println(utf8.RuneCountInString(s)) // "9"
  fmt.Println(s[0], s[7]) // "72 228"  ('H', '\x8c')

  // panic: index out of range
  // c := s[len(s)]

  fmt.Println(s[0:5]) // "Hello"
  fmt.Println(s[:5])  // "Hello"
  fmt.Println(s[7:])  // "世界"
  fmt.Println(s[8:])  // "??界"
  fmt.Println(s[:])   // "Hello, 世界"

  // "世界"
  // "\xe4\xb8\x96\xe7\x95\x8c"
  // "\u4e16\u754c"
  // "\U00004e16\U0000754c"
}
$ go run main.go
13
9
72 228
Hello
Hello
世界
??界
Hello, 世界

All escape characters

Within a double-quoted string literal, escape sequences that begin with a backslash \ can be used to insert arbitrary byte values into the string.

\a ‘‘alert’’ or bell
\b backspace
\f form feed
\n newline
\r carriage return
\t tab
\v vertical tab
\' single quote (only in the rune literal '\'')
\" double quote (only within "..." literals)
\\ backslash

Multiline strings

Simply use the backtick (`) character when declaring or assigning your string value.

package main

import "fmt"

func main() {

  s := `This is a
multiline
string.`

  fmt.Println(s)

}
$ go run main.go
This is a
multiline
string.

Related Tags

#use# #string#