5 Strings

 

This chapter covers

  • Understanding the fundamental concept of the rune in Go
  • Preventing common mistakes with string iteration and trimming
  • Avoiding inefficient code due to string concatenations or useless conversions
  • Avoiding memory leaks with substrings

In Go, a string is an immutable data structure holding the following:

  • A pointer to an immutable byte sequence
  • The total number of bytes in this sequence

We will see in this chapter that Go has a pretty unique way to deal with strings. Go introduces a concept called runes; this concept is essential to understand and may confuse newcomers. Once we know how strings are managed, we can avoid common mistakes while iterating on a string. We will also look at common mistakes made by Go developers while using or producing strings. In addition, we will see that sometimes we can work directly with []byte, avoiding extra allocations. Finally, we will discuss how to avoid a common mistake that can create leaks from substrings. The primary goal of this chapter is to help you understand how strings work in Go by presenting common string mistakes.

5.1 #36: Not understanding the concept of a rune

5.2 #37: Inaccurate string iteration

5.3 #38: Misusing trim functions

5.4 #39: Under-optimized string concatenation

5.5 #40: Useless string conversions

5.6 #41: Substrings and memory leaks

Summary