Beginner Fundamentals

Formatted Output

The fmt package is your main tool for printing values and building formatted text.

Println

Println prints its arguments separated by spaces and adds a newline.

fmt.Println("Name:", "Ada", "Age:", 30)
// Name: Ada Age: 30

Printf and verbs

Printf uses a format string with verbs as placeholders. It does not add a newline, so include \n yourself.

name := "Go"
version := 1.22
fmt.Printf("%s version %v\n", name, version)

Common verbs:

  • %v the value in a default format
  • %d an integer
  • %s a string
  • %f a float (use %.2f for two decimals)
  • %t a boolean
  • %T the type of the value
fmt.Printf("%d items cost $%.2f\n", 3, 9.5)
// 3 items cost $9.50

Sprintf

Sprintf returns the formatted text as a string instead of printing it.

label := fmt.Sprintf("User #%d", 42)
fmt.Println(label) // User #42