Go:Go Console I/O: fmt.Print, fmt.Println, and fmt.Printf
Go•Input/Output

Go Console I/O: fmt.Print, fmt.Println, and fmt.Printf

Master fmt format verbs: %v (default representation), %+v (struct fields), %s, %d, and %t.

Syntax

fmt.Printf("Verb %v\n", val)

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
%vFormat VerbPrints value in its default natural representation.
%+vFormat VerbPrints struct field names along with their values.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Go locally:

package main

import "fmt"

type ServiceMetric struct {
    Name    string
    Latency float64
    Healthy bool
}

func main() {
    metric := ServiceMetric{Name: "PostgresDB", Latency: 3.25, Healthy: true}

    // Comparing fmt format verbs
    fmt.Printf("Default %%v:   %v\n", metric)
    fmt.Printf("With fields %%+v: %+v\n", metric)
    fmt.Printf("Type %%T:        %T\n", metric)
}
Expected Output:
Default %v:   {PostgresDB 3.25 true}
With fields %+v: {Name:PostgresDB Latency:3.25 Healthy:true}
Type %T:        main.ServiceMetric

How It Works: Step-by-Step

  • Lines 5-9: Defines struct ServiceMetric.
  • Lines 14-16: Demonstrates %v, %+v, and %T format verbs.

Key Concepts

  • fmt.Printf supports powerful formatting verbs for inspecting any Go data structure.
  • %+v prints struct field names, making debugging fast.
  • %T prints the Go runtime data type of the expression.

Common Mistake: Using unexported (lowercase) struct fields when serializing or printing

Lowercase struct fields in Go are package-private; external packages like json cannot see them.

❌ Incorrect
type User struct { name string } // Private to package!
✅ Correct
type User struct { Name string } // Publicly exported

Related Go Tutorials & Compiler

Run and test Go on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Go Online Compiler