Start learning free

LESSON 60 OF 671 · STRINGS I

Updating Strings in Go

Lesson

Unlike some languages, strings in Go are immutable: once a string is created, its characters cannot be changed in place. Trying to assign to a character does not compile:

name := "bndrei Chiriac"

name[0] = 'A' // compile error: cannot assign to name[0] (neither addressable nor a map index expression)

Instead, we build a new string from the pieces we want, using slicing and concatenation, and assign it back to the variable:

name := "bndrei Chiriac"

name = "A" + name[1:] // a new string: "A" + everything after the first character

fmt.Println(name) // Output: Andrei Chiriac

The variable now points at the new string; the old one is discarded. This is why the assignment uses = on the whole variable, not on a single character.


Assignment
Someone made a typo while saving Andrei's name. Follow the Coding Tutorial and fix the first letter by building a new string.


Hint
Look at the slicing example above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check