Chapter 2. which code runs next?: Conditionals and Loops

image

Every program has parts that apply only in certain situations. “This code should run if there’s an error. Otherwise, that other code should run.” Almost every program contains code that should be run only when a certain condition is true. So almost every programming language provides conditional statements that let you determine whether to run segments of code. Go is no exception.

You may also need some parts of your code to run repeatedly. Like most languages, Go provides loops that run sections of code more than once. We’ll learn to use both conditionals and loops in this chapter!

Calling methods

In Go, it’s possible to define methods: functions that are associated with values of a given type. Go methods are kind of like the methods that you may have seen attached to “objects” in other languages, but they’re a bit simpler.

We’ll be taking a detailed look at how methods work in Chapter 9. But we need to use a couple methods to make our examples for this chapter work, so let’s look at some brief examples of calling methods now.

The time package has a Time type that represents a date (year, month, and day) and time (hour, minute, second, etc.). Each time.Time value has a Year method that returns the year. The code below uses this method to print the current year:

The time.Now function returns a new Time value for the ...

Get Head First Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.