Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Go Index

📄 fmt — Formatted I/O — print, scan, sprint

The most commonly used Go package. Implements formatted I/O similar to C's printf and scanf. Every Go program that produces output uses fmt. Import with import "fmt".

Import: import "fmt" | Docs: pkg.go.dev/fmt

📋 Functions, Types & Constants

NameSignature / ValueDescription
fmt.Printlnfunc Println(a ...any) (n int, err error)Print values with spaces and a newline
fmt.Printfunc Print(a ...any) (n int, err error)Print values with spaces, no newline
fmt.Printffunc Printf(format string, a ...any) (n int, err error)Print with format string
fmt.Sprintffunc Sprintf(format string, a ...any) stringFormat and return a string
fmt.Sprintlnfunc Sprintln(a ...any) stringFormat with newline, return string
fmt.Errorffunc Errorf(format string, a ...any) errorCreate a formatted error value
fmt.Fprintffunc Fprintf(w io.Writer, format string, a ...any) (n int, err error)Write formatted output to a Writer
fmt.Fprintlnfunc Fprintln(w io.Writer, a ...any) (n int, err error)Write values + newline to a Writer
fmt.Scanfunc Scan(a ...any) (n int, err error)Read space-separated values from stdin
fmt.Scanffunc Scanf(format string, a ...any) (n int, err error)Read formatted input from stdin
fmt.Scanlnfunc Scanln(a ...any) (n int, err error)Read values until newline from stdin
fmt.Sscanffunc Sscanf(str, format string, a ...any) (n int, err error)Read from a string
%vverbDefault format for any value
%+vverbStruct with field names
%#vverbGo-syntax representation
%TverbType of the value
%dverbInteger (base 10)
%fverbFloating-point decimal
%sverbString
%qverbQuoted string with Go escaping
%tverbBoolean (true or false)
%xverbInteger in hexadecimal
%bverbInteger in binary
%pverbPointer address
%everbScientific notation (e.g. 1.23e+08)
%02dverbZero-padded integer (width 2)
%-10sverbLeft-justified string in width 10

💡 Example Program

Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.

package main

import "fmt"

type Person struct {
    Name string
    Age  int
}

func main() {
    // Basic output
    fmt.Println("Hello, Go!")
    fmt.Printf("Pi is approximately %.4f\n", 3.14159)

    // Sprintf — build strings
    name := "Alice"
    msg  := fmt.Sprintf("Welcome, %s! You are visitor #%04d.", name, 42)
    fmt.Println(msg)

    // Struct formatting
    p := Person{"Bob", 30}
    fmt.Printf("Default : %v\n",  p)
    fmt.Printf("Fields  : %+v\n", p)
    fmt.Printf("Go-syntax: %#v\n", p)
    fmt.Printf("Type    : %T\n",  p)

    // Errorf
    err := fmt.Errorf("file %q not found (code %d)", "data.csv", 404)
    fmt.Println("Error:", err)

    // Input
    var age int
    fmt.Print("Enter your age: ")
    fmt.Scan(&age)
    fmt.Printf("You entered: %d\n", age)
}
// Compile & run: go run main.go
// Build binary:  go build -o hello main.go && ./hello

🏠 Index  |  os →