All lessons

Functions

9 min · Go

Package code under a name so you can reuse it.

Go · Functions0/5 cleared

Enemy 1 of 5

Go's function syntax

A function packages up reusable logic under a name, exactly like in every other language you've seen — but Go's declaration order reads a little differently. func double(n int) int puts the parameter's type right after its name (n int, not int n), and the return type comes after the closing parenthesis of the parameter list, not before the function's name.

This ordering — name first, then parameters, then return type — is a deliberate Go style choice, and it becomes especially handy once functions return multiple values (which you'll meet in a later lesson) or none at all (in which case the return type is simply omitted).

return hands a value back to the caller and ends the function immediately, just like in C, C++, and C#. Functions in Go don't have to appear above where they're called the way they do in C — Go's compiler reads the whole file first, so double could technically be defined below main too — but keeping helper functions above main, as shown here, is still the common convention for readability.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 10