Book Image

Hands-On Go Programming

By : Tarik Guney
Book Image

Hands-On Go Programming

By: Tarik Guney

Overview of this book

<p>With its C-like speed, simplicity, and power for a growing number of system-level programming domains, Go has become increasingly popular among programmers. Hands-On Go Programming teaches you the Go programming by solving commonly faced problems with the help of recipes. You will start by installing Go binaries and get familiar with the tools used for developing an application. Once you have understood these tasks, you will be able to manipulate strings and use them in built-in function constructs to create a complex value from two floating-point values. You will discover how to perform an arithmetic operation date and time, along with parsing them from string values. In addition to this, you will cover concurrency in Go, performing various web programming tasks, implementing system programming, reading and writing files, and honing many fundamental Go programming skills such as proper error handling and logging, among others. Whether you are an expert programmer or newbie, this book helps you understand how various answers are programmed in the Go language.</p>
Table of Contents (18 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributor
Preface
Index

The try...catch equivalent in Go


Unlike in other languages, there is no try...catch block in Go. In this section, we're going to see how Go handles basic errors. So, the first thing we're going to see is how to handle the errors returned by an API calls. We can use the time.Parse() method for that as it accepts a layout and a value string. It returns two things, one is the parsedDate and the other one is an error. Instead of returning an exception, Go returns an error as its second parameter most of the time.

 

 

Now, the way you can handle this is to check whether the parsedDate is nil. If it's not nil in Go, then we know that an error has happened and we need to handle it. If nothing happens, we can safely proceed to our next line, and that is to write the content of our parsedDate to output. So, for this, check the following code example:

package main

import (
  "time"
  "fmt"
)

func main(){
  parsedDate, err:= time.Parse("2006", "2018")
  if err != nil {
    fmt.Println("An error occured...