Skip to Content
Learning Go, 2nd Edition
book

Learning Go, 2nd Edition

by Jon Bodner
January 2024
Beginner
494 pages
12h 30m
English
O'Reilly Media, Inc.
Book available
Content preview from Learning Go, 2nd Edition

Chapter 4. Blocks, Shadows, and Control Structures

Now that I have covered variables, constants, and built-in types, you are ready to look at programming logic and organization. I’ll start by explaining blocks and how they control when an identifier is available. Then I’ll present Go’s control structures: if, for, and switch. Finally, I will talk about goto and the one situation when you should use it.

Blocks

Go lets you declare variables in lots of places. You can declare them outside of functions, as the parameters to functions, and as local variables within functions.

Note

So far, you’ve written only the main function, but you’ll write functions with parameters in the next chapter.

Each place where a declaration occurs is called a block. Variables, constants, types, and functions declared outside of any functions are placed in the package block. You’ve used import statements in your programs to gain access to printing and math functions (and I will talk about them in detail in Chapter 10). They define names for other packages that are valid for the file that contains the import statement. These names are in the file block. All the variables defined at the top level of a function (including the parameters to a function) are in a block. Within a function, every set of braces ({}) defines another block, and in a bit you will see that the control structures in Go define blocks of their own.

You can access an identifier defined in any outer block from within any inner block. This ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Designing Data-Intensive Applications, 2nd Edition

Designing Data-Intensive Applications, 2nd Edition

Martin Kleppmann, Chris Riccomini

Publisher Resources

ISBN: 9781098139285Errata PageSupplemental Content