Skip to content
String Basics
step 1/5

Reading — step 1 of 5

Learn

~2 min readStrings

String Basics

Strings look simple in every language and are simple in none of them. Go's design is unusually honest about what a string really is — an immutable sequence of bytes, usually holding UTF-8 text — and once you internalize those two words (immutable, bytes), every "weird" string behavior becomes predictable.

Immutable

go

You never modify a string; you compute new ones. Every function in the strings package returns a new string and leaves the original untouched:

go

Bytes, not characters

len(s) counts bytes. Indexing s[i] gives you a byte. For pure ASCII the distinction is invisible — and then the first é shows up:

go

When you need actual characters (Go calls them runes, i.e. Unicode code points), range decodes UTF-8 for you:

go

Working rules: len/indexing for protocols and ASCII, range (or []rune(s)) when human text is involved. For this course's graders — mostly ASCII — len does what you expect, but write code as if the é is coming, because in production it always is.

The strings package: your toolbox

Nearly every string task is a one-liner you should recognize on sight:

go

TrimSpace deserves a highlight: input read from stdin often carries an invisible trailing newline, and "hello\n" != "hello". When string comparisons mysteriously fail, trim first and re-examine.

Building and combining

+ concatenates: greeting := "Hello, " + name. For a handful of pieces that's perfect. For building a string in a loop, each + copies everything again (immutability!) — use strings.Builder:

go

One more literal worth knowing: backtick strings are raw — no escapes, newlines included literally — ideal for multi-line text and regex patterns: path := `C:\temp\new` keeps its backslashes.

Your exercise

Uppercase a word: read it (fmt.Scan(&word) conveniently stops at whitespace), transform with the right strings one-liner, print the returned value. It's three lines — and it forces the two habits this lesson exists for: reach for strings.X instead of hand-rolling loops, and never forget the result needs capturing because the original will not change.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

String Basics — Go Fundamentals