Go Strings Explained with Examples

Updated 4 min read
Go Strings featured image: cards for len, rune and strings.Builder

Go strings hold text, such as a user’s name or even a full web page. In this post, you will learn how text is stored and why its length can surprise you. You will also loop over characters and meet the helpers that save time. Also, each idea comes with a short example that you can run yourself.

You met the string type in Go variables, constants and data types. Text also behaves like a read-only slice, so review slices and arrays in Go will help.

What Are Go Strings?

In short, a string is a read-only sequence of bytes. In general, those bytes are UTF-8 text, the encoding that covers every language and emoji. Because the bytes are read-only, you can never change a string in place. Instead, you build a new one.

s := "Hello, Go"
fmt.Println(len(s))        // 9
fmt.Println(s[0])          // 72
fmt.Println(string(s[0]))  // H
fmt.Println(s[7:])         // Go

However, indexing with s[0] returns a byte, which is a number. So wrap it in string() to see the letter. Similarly, slicing with s[7:] works just like it does with slices.

Bytes vs Runes in Go Strings

A rune is one Unicode character, such as “a”, “é” or “🚀”. However, some characters need more than one byte. The diagram below shows how the bytes and runes line up for a short word.

Go Strings diagram showing 6 bytes grouped into 3 runes for the text Go plus a rocket emoji

“Go🚀” has 6 bytes but only 3 runes, because the rocket emoji takes 4 bytes in UTF-8.

city := "Pune 🚀"
fmt.Println(len(city))         // 9  (bytes)
fmt.Println(len([]rune(city))) // 6  (characters)

So len counts bytes, not characters. Therefore, to count characters, convert to []rune first.

Looping with range

for i, r := range "Go🚀" {
	fmt.Println(i, string(r))
}
// 0 G
// 1 o
// 2 🚀

In contrast, range decodes one rune at a time. Since the index i is the byte position, it jumps.

Raw Strings with Backticks

path := `C:\Users\asha\notes.txt`
query := `SELECT name
FROM users`

First of all, double quotes understand escapes like \n for a new line. Backticks, however, keep every character exactly as typed and can span many lines. So they are perfect for file paths, SQL and regular expressions.

Comparing Go Strings

fmt.Println("go" == "go")    // true
fmt.Println("apple" < "banana") // true
fmt.Println("Go" == "go")    // false

Also, you compare Go strings with ==, < and >, just like numbers. The comparison works byte by byte, so capital letters sort before small ones. As a result, “Go” and “go” are different values.

The strings Package

For example, these helpers cover most daily work with text.

strings.Contains("Hello, Go", "Go")             // true
strings.ToUpper("go")                           // GO
strings.Split("a,b,c", ",")                     // [a b c]
strings.Join([]string{"go", "is", "fun"}, " ")  // go is fun
strings.Replace("aaa", "a", "b", 2)             // bba
strings.TrimSpace("  hi  ")                     // hi
strings.Fields(" learn   go  fast ")            // [learn go fast]
strings.HasPrefix("golang", "go")               // true

Also, strings.EqualFold("Go", "GO") compares text without caring about case, which suits usernames and emails.

Building Go Strings Efficiently

var b strings.Builder
for i := 1; i <= 3; i++ {
	fmt.Fprintf(&b, "item%d ", i)
}
fmt.Println(b.String()) // item1 item2 item3

Every + creates a brand new string and copies the old bytes. As a result, that waste adds up fast in a big loop. A strings.Builder instead grows one buffer, so it is much faster for Go strings built piece by piece.

Converting Numbers and Text

n, err := strconv.Atoi("42")
fmt.Println(n+1, err) // 43 <nil>

_, err = strconv.Atoi("42a")
fmt.Println(err) // strconv.Atoi: parsing "42a": invalid syntax

fmt.Println(strconv.Itoa(7) + "7") // 77

Meanwhile, the strconv package turns text into numbers and back. Since user input can be anything, always check the error from Atoi.

Changing a Character

bs := []byte("Hello, Go")
bs[0] = 'J'
fmt.Println(string(bs)) // Jello, Go

To edit text, first convert it to a byte slice, change it and then convert it back. For text with emoji or accents, use []rune instead.

Common Mistakes with Go Strings

Problem you seeWhy it happensHow to fix it
cannot assign to s[0] (neither addressable nor a map index expression)Because strings are read-only.So convert to []byte or []rune first.
Length is bigger than expectedBecause len counts bytes.So use len([]rune(s)).
Broken emoji when slicingBecause the slice cut a rune in half.So slice a []rune, not the string.
Slow loop building textBecause + copies every time.So use strings.Builder.

In fact, text questions show up in many coding rounds. So practise them with my Go interview questions and answers.

Official Resources

These pages come straight from the Go team, so they stay accurate and up to date.

Quick Recap

  • Go strings are read-only sequences of UTF-8 bytes.
  • len counts bytes, while []rune counts characters.
  • range over text gives you one rune at a time.
  • The strings package handles search, split, join and trim.
  • Use strings.Builder in loops and strconv for numbers.

What’s Next?

At last, you can handle text with confidence. Next, we will learn about functions without names that remember values, known as closures.

Next lesson: Go Closures and Anonymous Functions Explained