Skip to content
Functions
step 1/5

Reading — step 1 of 5

Learn

~3 min readFunctions

Functions

Functions are where Go's "boring on purpose" philosophy pays off: the syntax holds no surprises, the semantics fit in your head, and one signature convention (multiple returns — previewed here, starring in chapter 6) organizes the entire language's error handling.

The shape

go

Types come after names — a int, not int a — and the return type sits after the parameter list. Reading signatures aloud helps them stick: "add takes a and b, ints, and returns an int."

go

A function that promises a return type must return on every path — a missing return is a compile error, not a runtime surprise.

Arguments are copies

Go passes by value: the function gets copies of what you pass.

go

The right response is usually not "how do I get around that" but "return the new value" (x = doubled(x)), which keeps data flow visible. When you genuinely need to mutate the caller's variable, pointers do it explicitly (chapter 6) — the & you've been giving fmt.Scan is exactly that.

Multiple return values

Go functions can return several values, and the language leans on this hard:

go

Where other languages return special values (-1, null) or throw exceptions, Go returns the answer and the status side by side — value, err := … — the pattern the next lesson is entirely about. divmod is that pattern with the training wheels on.

First-class values

Functions are values: assign them, pass them, return them.

go

You don't need this today, but you'll meet it soon — sort.Slice takes a comparison function, http.HandleFunc takes a handler — so recognize the shape when it appears.

Your exercise: Square It

Write square(n int) int, call it from main with input from stdin, print the result. Trivial math; the graded skill is the separation — logic in a function, I/O in main:

go

Resist computing in main "because it's shorter." Every exercise from here on assumes you can define a function to spec, and every real program you write will live or die by keeping compute (testable, reusable) separate from I/O (glue). Start the habit where it's easy.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…