Chapter 6. String Recipes

6.0 Introduction

String manipulation is one of the most common tasks in any programming language. Most programs deal with text in one way or another, whether directly interacting with users or communicating between machines. Text is probably the closest thing we have to a universal medium, and string as data is everywhere. Being able to manipulate strings is a critical capability in your arsenal as a programmer.

Go has several packages used for string manipulation. The strconv package focuses on converting to or from strings. The fmt package provides functions to format strings using verbs as replacements, much like in C. The unicode/utf8 and unicode/utf16 packages have functions used in Unicode-encoded strings. The strings package has functions to do many of the string manipulations we see so if you’re not sure what you need, that’s the most likely location to look.

6.1 Creating Strings

Problem

You want to create strings.

Solution

Use either the double quotes ("") or the backtick (or backquote) (``) to create string literals. Use the single quotes ('') to create character literals.

Discussion

In Go, string is a read-only (immutable) slice of bytes. It can be any byte and doesn’t need to be in any encoding or format. This is unlike other programming languages, where strings are sequences of characters. In Go, a character can be represented by more than a single byte. This is in line with the Unicode standard, which defines a code point to represent ...

Get Go Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.