One-liners

Contents

One-liners#

Single-expression idioms the operator pastes into a Go scratch file.

Print to stderr without importing log.

fmt.Fprintln(os.Stderr, "msg")

Read a whole file in one expression.

b, err := os.ReadFile("notes.txt")

Write a whole file in one expression.

err := os.WriteFile("out.bin", payload, 0644)

Build a string with strings.Join; avoid + in a loop.

joined := strings.Join(parts, ",")

Parse an integer or fail.

n, err := strconv.Atoi(s)

Range a slice and capture the index and value.

for i, v := range xs { use(i, v) }

Inline conditional via a function (Go has no ternary).

func ifelse[T any](c bool, a, b T) T { if c { return a }; return b }

Defer a cleanup so it runs on every exit path.

f, err := os.Open(p); if err != nil { return err }
defer f.Close()

Open a TCP connection with a timeout.

conn, err := net.DialTimeout("tcp", "example.com:443", 3*time.Second)

References#

  • Snippets for the snippets catalogue.

  • Types for the underlying types.