Skip to content

Go fmt API

Go fmt package — formatted I/O with C-style verbs.

1 class · 7 methods

fmt

7 methods

Package 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

NameTypeDescription
a...anyOperands 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

NameTypeDescription
a...anyOperands 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

NameTypeDescription
formatstringFormat string (e.g. %v, %d, %s).
a...anyOperands.

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) string

Return a string (instead of printing) according to a format specifier.

Parameters

NameTypeDescription
formatstringFormat string.
a...anyOperands.

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

NameTypeDescription
wio.WriterWriter target.
formatstringFormat string.
a...anyOperands.

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.Buffer
fmt.Scanf(format string, a ...any) (n int, err error)

Scan text read from standard input, storing successive space-separated values into successive arguments.

Parameters

NameTypeDescription
formatstringFormat string.
a...anyPointers 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=30
fmt.Errorf(format string, a ...any) error

Return an error that formats according to a format specifier. Wraps with %w.

Parameters

NameTypeDescription
formatstringFormat string (use %w to wrap an error).
a...anyOperands.

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