Go📦Standard Libraryintermediate
fmt — Formatted I/O
Go · Standard Library · Run with go run
Explanation
The `fmt` package implements formatted I/O. `fmt.Printf` writes formatted text to stdout; `fmt.Sprintf` returns it as a string. Go's format verbs: `%v` (default value), `%+v` (struct with field names), `%#v` (Go syntax), `%T` (type), `%d` (integer), `%s` (string), `%q` (quoted string), `%x` (hex), `%f` (float), `%p` (pointer).
Real-World Scenario
Logging a request: `log.Printf("method=%s path=%s status=%d latency=%v", r.Method, r.URL.Path, status, time.Since(start))` — structured key=value pairs with mixed verb types in one call.
Quick Snippet
snippet.go
import "fmt"
type User struct{ Name string; Age int }
u := User{"Alice", 30}
fmt.Printf("%v\n", u) // {Alice 30}
fmt.Printf("%+v\n", u) // {Name:Alice Age:30}
fmt.Printf("%#v\n", u) // main.User{Name:"Alice", Age:30}
fmt.Printf("%T\n", u) // main.User
// Errorf wraps errors with context
err := fmt.Errorf("load user %d: %w", 42, ErrNotFound)
// Sscanf parses formatted input
var name string; var age int
fmt.Sscanf("Alice 30", "%s %d", &name, &age)Full Example
fmt_basics.go
// Compile: go run fmt_basics.go
// Output:
// {Alice 30}
// {Name:Alice Age:30}
// main.User{Name:"Alice", Age:30}
// main.User
// parsed: Bob 25
package main
import "fmt"
type User struct {
Name string
Age int
}
func main() {
u := User{"Alice", 30}
fmt.Printf("%v\n", u) // default
fmt.Printf("%+v\n", u) // field names
fmt.Printf("%#v\n", u) // Go syntax
fmt.Printf("%T\n", u) // type
// Sscanf parses formatted input
var name string
var age int
fmt.Sscanf("Bob 25", "%s %d", &name, &age)
fmt.Printf("parsed: %s %d\n", name, age)
}
Run command
go run fmt_basics.go