WeCodeAcademy

Go Printf Verbs and strings.Builder

ExampleGo
package main

import (
  "fmt"
  "strings"
)

type Point struct{ X, Y int }

func main() {
  p := Point{3, 4}
  fmt.Printf("%v | %+v | %#v | %T\n", p, p, p, p)
  fmt.Printf("%d|%5d|%-5d|%05d\n", 42, 42, 42, 42)
  fmt.Printf("%.2f|%8.3f|%e\n", 3.14159, 3.14159, 1234.5678)
  fmt.Printf("%s|%q|%x|%c\n", "hi", "hi", 255, 'G')
  fmt.Printf("%t %%\n", true)

  var sb strings.Builder
  for i := 1; i <= 3; i++ {
    fmt.Fprintf(&sb, "[%d]", i)
  }
  fmt.Println(sb.String())
}
Output
{3 4} | {X:3 Y:4} | main.Point{X:3, Y:4} | main.Point
42|   42|42   |00042
3.14|   3.142|1.234568e+03
hi|"hi"|ff|G
true %
[1][2][3]

A strings.Builder builds a string efficiently, much better than adding to a string in a loop.

Quick check

Which verb prints a value with its field names?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.