Next: Working with Command-Line Arguments, Previous: Go Packages and the Standard Library, Up: Tutorial [Index]
A function declaration consists of the keyword func
, the name of the
function, a parameter list (empty for main
), a result list (also empty here),
and the body of the function—the statements that define what it
does—enclosed in braces. We’ll take a closer look at functions in Chapter 5.
Go does not require semicolons at the ends of statements or declarations,
except where two or more appear on the same line. In effect, newlines
following certain tokens are converted into semicolons, so where newlines are
placed matters to proper parsing of Go code. For instance, the opening brace
‘{’ of the function must be on the same line as the end of the func
declara-
tion, not on a line by itself, and in the expression ‘x + y’, a newline is
permitted after but not before the ‘+’ operator.
gofmt
ToolGo takes a strong stance on code formatting. The gofmt
tool rewrites code
into the standard format, and the go
tool’s fmt
subcommand applies gofmt
to all the files in the specified package, or the ones in the current directory
by default. All Go source files in the book have been run through gofmt
, and
you should get into the habit of doing the same for your own code. Declaring a
standard format by fiat eliminates a lot of pointless debate about trivia and,
more importantly, enables a variety of automated source code transformations
that would be infeasible if arbitrary formatting were allowed.
Many text editors can be configured to run gofmt
each time you save a file,
so that your source code is always properly formatted.
goimports
ToolA related tool, goimports
, additionally manages the insertion and removal of
import
declarations as needed. It is not part of the standard distribution
but you can obtain it with this command:
$ go get golang.org/x/tools/cmd/goimports
For most users, the usual way to download and build packages, run their tests, show their documentation, and so on, is with the go tool, which we’ll look at in Section 10.7.
Next: Working with Command-Line Arguments, Previous: Go Packages and the Standard Library, Up: Tutorial [Index]