Getting started with Go — Continued

Matthew Boyd
2 min readDec 23, 2021

--

Continuing on from the last article, there are a few more tips and tricks to teach you.

For imports, we can write them in a much clearer way if we have multiple imports:

Old way:

import "fmt"
import "time"

New way:

import (
"fmt"
"time"
)

This will keep our code cleaner and more concise.

We can also do the same trick with variables and constants:

var (name stringage intaddress stringmarried bool)

and similarly with constants:

package main import "fmt"const (
name string = "Matthew"
)
func main(){
fmt.Println(name)
}

Functions:

Functions are pretty similar to most other languages, we can have parameter-less functions:

func HelloWorld(){fmt.Println("hello, world!")
}
  • Notice the capitalisation of the function name, this means that the function is exported, this is similar to the premise of public and private methods. If the variable / function starts with a lower case, then it is a private method and can only be used in that package. However, if it is a capitalised name, like HelloWorld, we can use this else where.

Input parameter function:

func incrementByOne(number int){    number += 1    fmt.Println(number)}

This function takes in a named parameter called number which is of type int and it will increase the number that it received by one and then prints that value out to the screen.

Return value functions:

func incrementByOne(number int) int{    number += 1    return number}

As you can see there are two differences from the last example, the first is that instead of printing the value, we are returning that. In order to return the value, we have to tell Go that in this method, it will be returning a value, and we have to tell it the type of value it’s returning. Therefore, after the input parameters in brackets, we have specified that it will return an int.

Multiple Return Values:

func incrementByOne(number, test int) (int, int) {    number += 1    return number, test}

In this example, we’re returning two int values.

--

--