Text and Formatting
What you will learn
- format values with
fmt; - search and transform text with
strings; - distinguish bytes from Unicode code points;
Text in Go is usually stored in a string. A string is a read-only sequence of bytes, commonly containing UTF-8 text.
Print with fmt
name := "Mira"
lessons := 12
fmt.Println("Learner:", name)
fmt.Printf("%s completed %d lessons\n", name, lessons)
message := fmt.Sprintf("%s: %d", name, lessons)
Printlnseparates values with spaces and adds a newline.Printfwrites according to a format string.Sprintfreturns the formatted string instead of printing it.
Useful verbs include:
| Verb | Meaning |
|---|---|
%s | string |
%d | decimal integer |
%f | floating-point number |
%t | boolean |
%v | default value representation |
%T | Go type |
%q | quoted string or character |
Search and transform with strings
title := " Learning Go "
title = strings.TrimSpace(title)
fmt.Println(strings.ToUpper(title))
fmt.Println(strings.Contains(title, "Go"))
fmt.Println(strings.ReplaceAll(title, "Go", "Golang"))
Split and join structured text:
parts := strings.Split("api,worker,cli", ",")
joined := strings.Join(parts, " | ")
Use strings.Builder when repeatedly constructing a large string in a loop.
Convert with strconv
port, err := strconv.Atoi("8080")
if err != nil {
return fmt.Errorf("parse port: %w", err)
}
text := strconv.Itoa(port)
enabled, err := strconv.ParseBool("true")
Parsing can fail, so handle the error. Formatting a known value with functions such as Itoa does not fail.
Bytes, runes, and characters
len(text) counts bytes, not human-visible characters.
word := "Go世界"
fmt.Println(len(word)) // bytes
fmt.Println(utf8.RuneCountInString(word)) // Unicode code points
A rune is an alias for int32 and represents one Unicode code point.
for index, r := range word {
fmt.Printf("byte index %d: %q\n", index, r)
}
The index from ranging over a string is a byte index. Convert to []rune when you genuinely need to index code points, while remembering that one user-perceived character may contain several code points.
Strings are immutable
You cannot change a byte inside a string directly. Convert to []byte for byte-level changes or []rune for code-point-level changes, then convert back.
Practice
Accept a comma-separated line such as alice, bob,CHARLIE. Split it, trim spaces, normalise each name to title case using a simple first-letter rule, and join the names with |.
strconv, and return parsing errors rather than substituting zero. When iterating human-readable text, range yields rune positions and values; indexing yields bytes.Summary
- Use formatting verbs that match the value and output purpose.
- Strings are immutable byte sequences, while
rangedecodes UTF-8 runes. - Parsing is fallible and its errors belong in the program's control flow.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.