fmt
7 methodsPackage fmt implements formatted I/O with functions analogous to C's printf and scanf.
fmt.Print(a ...any) (n int, err error)Print using default formats for each operand. Spaces added between operands when neither is a string.
Parameters
| Name | Type | Description |
|---|---|---|
| a | ...any | Operands to print. |
Returns
(int, error)
Example
go
fmt.Print("a", "b", 1) // "ab 1"
fmt.Print(1, 2, 3) // "1 2 3"fmt.Println(a ...any) (n int, err error)Print using default formats, with spaces between operands and a newline at the end.
Parameters
| Name | Type | Description |
|---|---|---|
| a | ...any | Operands to print. |
Returns
(int, error)
Example
go
fmt.Println("hello", "world") // "hello world\n"
fmt.Println(1, 2, 3) // "1 2 3\n"fmt.Printf(format string, a ...any) (n int, err error)Print according to a format specifier.
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | Format string (e.g. %v, %d, %s). |
| a | ...any | Operands. |
Returns
(int, error)
Example
go
fmt.Printf("%s is %d\n", "Alice", 30) // "Alice is 30\n"
fmt.Printf("%v\n", []int{1, 2}) // "[1 2]\n"
fmt.Printf("%-4d|%-4d\n", 1, 2) // "1 |2 \n"fmt.Sprintf(format string, a ...any) stringReturn a string (instead of printing) according to a format specifier.
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | Format string. |
| a | ...any | Operands. |
Returns
string
Example
go
s := fmt.Sprintf("%s is %d", "Alice", 30)
// s == "Alice is 30"fmt.Fprintf(w io.Writer, format string, a ...any) (n int, err error)Write to w according to a format specifier.
Parameters
| Name | Type | Description |
|---|---|---|
| w | io.Writer | Writer target. |
| format | string | Format string. |
| a | ...any | Operands. |
Returns
(int, error)
Example
go
fmt.Fprintf(os.Stdout, "%d%%\n", 50) // writes "50%\n" to stdout
fmt.Fprintf(buf, "x=%d", 1) // writes to a bytes.Bufferfmt.Scanf(format string, a ...any) (n int, err error)Scan text read from standard input, storing successive space-separated values into successive arguments.
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | Format string. |
| a | ...any | Pointers to receive values. |
Returns
(int, error)
Example
go
var name string
var age int
fmt.Scanf("%s %d", &name, &age)
// input: "Alice 30" → name="Alice", age=30fmt.Errorf(format string, a ...any) errorReturn an error that formats according to a format specifier. Wraps with %w.
Parameters
| Name | Type | Description |
|---|---|---|
| format | string | Format string (use %w to wrap an error). |
| a | ...any | Operands. |
Returns
error
Example
go
err := fmt.Errorf("user %d not found", 42)
// err.Error() == "user 42 not found"
// wrapping:
wrapped := fmt.Errorf("query failed: %w", err)
// errors.Is(wrapped, err) == true