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
| Name | Signature / Value | Description |
|---|---|---|
| fmt.Println | func Println(a ...any) (n int, err error) | Print values with spaces and a newline |
| fmt.Print | func Print(a ...any) (n int, err error) | Print values with spaces, no newline |
| fmt.Printf | func Printf(format string, a ...any) (n int, err error) | Print with format string |
| fmt.Sprintf | func Sprintf(format string, a ...any) string | Format and return a string |
| fmt.Sprintln | func Sprintln(a ...any) string | Format with newline, return string |
| fmt.Errorf | func Errorf(format string, a ...any) error | Create a formatted error value |
| fmt.Fprintf | func Fprintf(w io.Writer, format string, a ...any) (n int, err error) | Write formatted output to a Writer |
| fmt.Fprintln | func Fprintln(w io.Writer, a ...any) (n int, err error) | Write values + newline to a Writer |
| fmt.Scan | func Scan(a ...any) (n int, err error) | Read space-separated values from stdin |
| fmt.Scanf | func Scanf(format string, a ...any) (n int, err error) | Read formatted input from stdin |
| fmt.Scanln | func Scanln(a ...any) (n int, err error) | Read values until newline from stdin |
| fmt.Sscanf | func Sscanf(str, format string, a ...any) (n int, err error) | Read from a string |
| %v | verb | Default format for any value |
| %+v | verb | Struct with field names |
| %#v | verb | Go-syntax representation |
| %T | verb | Type of the value |
| %d | verb | Integer (base 10) |
| %f | verb | Floating-point decimal |
| %s | verb | String |
| %q | verb | Quoted string with Go escaping |
| %t | verb | Boolean (true or false) |
| %x | verb | Integer in hexadecimal |
| %b | verb | Integer in binary |
| %p | verb | Pointer address |
| %e | verb | Scientific notation (e.g. 1.23e+08) |
| %02d | verb | Zero-padded integer (width 2) |
| %-10s | verb | Left-justified string in width 10 |
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