0Pricing
Go Academy · Lesson

fmt and strings Packages

Formatting output and manipulating strings

fmt and strings Packages is a free Go Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The fmt Package Overview

The fmt package implements formatted I/O. Key functions:

  • fmt.Print, fmt.Println, fmt.Printf — write to stdout
  • fmt.Sprint, fmt.Sprintf, fmt.Sprintln — return strings
  • fmt.Fprint, fmt.Fprintf — write to any io.Writer
  • fmt.Scan, fmt.Scanf — read from stdin

fmt Format Verbs

Common format verbs for fmt.Printf:

package main
import "fmt"

func main() {
    name := "Gopher"
    age := 15
    score := 98.6

    fmt.Printf("%s is %d years old\n", name, age)
    fmt.Printf("Score: %.1f%%\n", score)
    fmt.Printf("Type: %T, Value: %v\n", age, age)
    fmt.Printf("Hex: %x, Binary: %b\n", 255, 255)
    fmt.Printf("Padded: %10s|%-10s\n", name, name)
}

fmt.Sprintf for String Building

fmt.Sprintf returns a formatted string without printing it — useful for building strings:

package main
import "fmt"

func formatUser(name string, age int) string {
    return fmt.Sprintf("User{name: %q, age: %d}", name, age)
}

func main() {
    fmt.Println(formatUser("Alice", 30))
    // User{name: "Alice", age: 30}

    // %q adds quotes; %+v prints struct field names
    type Point struct{X, Y int}
    p := Point{1, 2}
    fmt.Printf("%+v\n", p) // {X:1 Y:2}
}

fmt.Errorf for Error Formatting

fmt.Errorf creates formatted error values:

package main
import "fmt"

func getUser(id int) error {
    return fmt.Errorf("getUser(%d): user not found", id)
}

func main() {
    err := getUser(42)
    fmt.Println(err) // getUser(42): user not found

    // Wrap errors with %w for unwrapping:
    base := fmt.Errorf("base error")
    wrapped := fmt.Errorf("context: %w", base)
    fmt.Println(wrapped)
}

strings Package: Common Functions

The strings package provides string manipulation functions:

package main
import ("fmt"; "strings")

func main() {
    s := "  Hello, Go World!  "

    fmt.Println(strings.TrimSpace(s))           // "Hello, Go World!"
    fmt.Println(strings.ToUpper(s))             // "  HELLO, GO WORLD!  "
    fmt.Println(strings.ToLower(s))             // "  hello, go world!  "
    fmt.Println(strings.Contains(s, "Go"))      // true
    fmt.Println(strings.HasPrefix(s, "  Hel")) // true
    fmt.Println(strings.Count(s, "l"))          // 3
}

strings.Split and strings.Join

strings.Split splits a string, strings.Join joins a slice:

package main
import ("fmt"; "strings")

func main() {
    csv := "alice,bob,carol,dave"
    names := strings.Split(csv, ",")     // ["alice" "bob" "carol" "dave"]
    fmt.Println(names)

    upper := make([]string, len(names))
    for i, n := range names {
        upper[i] = strings.ToUpper(n)
    }
    result := strings.Join(upper, " | ")
    fmt.Println(result) // ALICE | BOB | CAROL | DAVE
}

strings.Replace and strings.ReplaceAll

Replace occurrences of a substring:

package main
import ("fmt"; "strings")

func main() {
    s := "foo bar foo baz foo"

    // Replace first 2 occurrences
    fmt.Println(strings.Replace(s, "foo", "XXX", 2))
    // XXX bar XXX baz foo

    // Replace all
    fmt.Println(strings.ReplaceAll(s, "foo", "GO"))
    // GO bar GO baz GO
}

strings.Builder for Efficient Concatenation

Use strings.Builder to build strings efficiently — avoids allocating a new string for every concatenation:

package main
import ("fmt"; "strings")

func join(parts []string, sep string) string {
    var sb strings.Builder
    for i, p := range parts {
        if i > 0 { sb.WriteString(sep) }
        sb.WriteString(p)
    }
    return sb.String()
}

func main() {
    fmt.Println(join([]string{"a", "b", "c"}, "-")) // a-b-c
}

strings.NewReader and strings.Reader

strings.NewReader creates an io.Reader from a string — useful for testing functions that accept readers:

package main
import ("fmt"; "io"; "strings")

func readAll(r io.Reader) string {
    data, _ := io.ReadAll(r)
    return string(data)
}

func main() {
    r := strings.NewReader("Hello from a string reader")
    fmt.Println(readAll(r))

    // Also: strings.NewReplacer for multiple replacements
    rep := strings.NewReplacer("<", "&lt;", ">", "&gt;")
    fmt.Println(rep.Replace("<b>bold</b>"))
}

strings.Fields and strings.Map

Additional useful strings functions:

package main
import ("fmt"; "strings")

func main() {
    // Fields splits on any whitespace (like awk)
    words := strings.Fields("  one  two   three  ")
    fmt.Println(words) // [one two three]

    // Map applies a function to each rune
    rot13 := func(r rune) rune {
        if r >= 'a' && r <= 'z' { return 'a' + (r-'a'+13)%26 }
        if r >= 'A' && r <= 'Z' { return 'A' + (r-'A'+13)%26 }
        return r
    }
    fmt.Println(strings.Map(rot13, "Hello, World!"))
}

Quick Check

Which function should you use to efficiently concatenate many strings in Go?

Recap: fmt and strings

Summary:

  • fmt.Printf/Sprintf for formatted output/strings with format verbs (%s %d %f %v %T %q)
  • fmt.Errorf for formatted errors, %w to wrap
  • strings.Split/Join, Contains, Replace, TrimSpace, ToUpper/Lower
  • strings.Builder for efficient concatenation
  • strings.NewReader to use string as io.Reader

Frequently asked questions

Is the “fmt and strings Packages” lesson free?

Yes — the full text of “fmt and strings Packages” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.

What will I learn in “fmt and strings Packages”?

Formatting output and manipulating strings You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Go Academy?

No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “fmt and strings Packages” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Go Academy lesson?

Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. fmt and strings Packages
  2. strconv, math and sort
  3. time Package Essentials
  4. os and filepath Packages
← Back to Go Academy