Search⌘ K
AI Features

Strings

Explore the fundamentals of strings in Go, focusing on their UTF-8 variable-width encoding, immutability, and how to work with interpreted and raw string literals. Understand string length, indexing, and concatenation to build a solid foundation for handling text in Go programs.

Introduction

Strings are a sequence of UTF-8 characters (the 1-byte ASCII-code is used when possible, and a 2-4 byte UTF-8 code when necessary). UTF-8 is the most widely used encoding. It is the standard encoding for text files, XML files, and JSON strings. With string data type, you can reserve 4 bytes for characters, but Go is intelligent enough that it will reserve one-byte if the string is only an ASCII character.

Strings in Go

Contrary to strings in other languages as C++, Java or Python that are fixed-width (Java always uses 2 bytes), a Go string is a sequence of variable-width characters (each 1 to 4 bytes).

Advantages of strings

The advantages of strings are:

  • Go strings and text files occupy less memory/disk space (because of variable-width characters).
  • Since UTF-8 is the standard, Go doesn’t need to encode and decode strings like other languages have to do.

Strings are value types and immutable, which means that once created, you cannot modify the contents of the string. In other words, strings are immutable arrays of bytes.

Types of string literals

Two kinds of ...