Text: Sprintf and the strings functions
So far we've only stored text (Title string) and printed it. Now we learn to work with it — because a real program constantly builds, compares and tidies text.
Formatting with fmt.Sprintf. Println prints; Sprintf does the same but returns a string, so you can store it or use it further:
line := fmt.Sprintf("Book: %s (%d pages)", it.Title, it.Pages)
// line == "Book: The Go Programming Language (380 pages)"
The most useful verbs: %s — a string, %d — an integer, %v — any value, %.1f — a float with one decimal, %q — a quoted string. And for alignment: %-30s — left-aligns text, padding to 30 columns (so a list of rows lines up).
The most common strings functions (import "strings"):
strings.ToLower("Go") // "go"
strings.Contains(t, "prog") // is the substring present?
strings.HasPrefix(t, "The ") // does it start with...?
strings.TrimSpace(" hello \n") // "hello" — strips spaces/newlines
strings.ReplaceAll(t, " ", "-") // replace every space with a hyphen
strings.Split("a,b,c", ",") // []string{"a", "b", "c"}
strings.Join([]string{"a","b"}, ", ") // "a, b"
Comparing. A plain == compares exactly (case-sensitive). For a case-insensitive compare, strings.EqualFold("Go", "go") returns true.
We'll apply these right away: Sprintf for a clean record display, Split/TrimSpace for tidying user input. But first — the gotcha that can make len deceive you.