Strings
Start with Go Strings
A Go string represents an immutable sequence of bytes, conventionally holding UTF-8 encoded text. Strings are convenient for names, messages and other text data.
What you’ll learn
- Explain the main purpose of go strings.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Use double quotes for an interpreted string literal, such as "Hello\nGo", where backslash escapes have special meaning. Use backticks for a raw string literal whose content is preserved more literally, including newlines.
String values are immutable: you cannot assign to name[0]. To transform text, build a new string or work with bytes or runes before converting back. A string can contain bytes that are not valid UTF-8; Go does not automatically validate them.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
greeting := "Hello"
language := "Go"
message := greeting + ", " + language + "!"
fmt.Println(message)
raw := `Line one\nLine two`
fmt.Println(raw)
}
Output
Hello, Go!
Line one\nLine twoTrace what the program does
The + operator builds a new greeting string. The raw literal contains the characters backslash and n, so it prints those literal characters rather than making a newline. The original greeting and language strings are unchanged.
Avoid common mistakes
- A string is immutable; assign a newly constructed string instead of trying to change an indexed byte.
- String length measures bytes, not necessarily visible characters.
Try it yourself
Create a string with an accented word or an emoji. Print the string and compare its byte length with an ASCII word.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Go Strings in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.