Learn Go← Dashboard

fmt, io, os, bufio, encoding/json, net/http, time, slog, regexp, flag, embed.

fmt and io

The fmt package is your one-stop print/format/scan library.

Print family

fmt.Print("a", " ", "b")       // "a b"     — no newline
fmt.Println("a", "b")          // "a b\n"   — adds newline and spaces between args
fmt.Printf("count=%d\n", 5)    // formatted

Format verbs

| Verb | Meaning | Example | | ----- | ---------------------------------------- | ---------------------- | | %v | Default format — works for almost anything | fmt.Printf("%v", x) | | %+v | Like %v, with struct field names | {Name:Ada} | | %#v | Go syntax representation | main.User{Name:"Ada"} | | %T | Type of the value | int, *User | | %d | Decimal integer | 42 | | %b | Binary | 101010 | | %o | Octal | 52 | | %x | Hex (lowercase) — %X uppercase | 2a | | %f | Float, default precision | 3.140000 | | %.2f| Float, 2 decimal places | 3.14 | | %s | String | "hello" | | %q | Quoted string | "hello" | | %c | Character (rune) | A | | %t | Boolean | true | | %p | Pointer | 0xc0000180a0 | | %w | Wrap error (in fmt.Errorf only) | |

go playground
Loading...

Sprint and Fprintf

  • fmt.Sprint* — return the formatted result as a string.
  • fmt.Fprint* — write to any io.Writer.
msg := fmt.Sprintf("user %s logged in", name)
fmt.Fprintf(os.Stderr, "warning: %v\n", err)

io.Reader and io.Writer

These two interfaces are the backbone of Go I/O.

type Reader interface { Read(p []byte) (n int, err error) }
type Writer interface { Write(p []byte) (n int, err error) }

Files, network sockets, buffers, gzip streams, encryption layers — everything is one of these. A function that takes io.Reader works with all of them.

n, err := io.Copy(dst, src)    // copy until EOF or error
b, err := io.ReadAll(r)        // read into a []byte

EOF: not really an error

io.EOF is a sentinel error returned when a Read runs out of bytes — it signals success ("end of stream"), not failure. Compare with errors.Is(err, io.EOF).

Which verb prints a struct with its field names included? e.g. `{Name:Ada Age:36}`?