O'Reilly logo

Head First Go by Jay McGavren

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2 conditionals and loops

Which Code Runs Next?

Images

Every program has parts that only apply 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 much simpler.

We'll be taking a detailed look at how methods work in chapter TODO. 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 current date and ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required