Continue Going With Go

A few months ago, I wrote an intro to Golang. I only covered how to install and a basic "Hello, World" program with variables. In today's post, I am going to extend that and cover functions.

Last time, we had one function:

func main() {
    var name string := "Antony"
    fmt.Println("Hello, " + name + "!")
}

As you can see, it is declared with the func key word and a name. So far straight forward.

So I can rewrite the above function to be a separate function. Like so:

func main() {
    fmt.Println(generateOutput("Antony"))
}

func generateOutput(name string) string {
    return "Hello, " + name + "!"
}

generateOutput takes a single parameter which has to be of type "string". Also, it's return type is declared as being "string".

You can see that I am using generateOutput in the main function in the place of a string. Hopefully, it is all very straightforward how this comes together.

You can actually declare multiple return types for functions. Here is a really simple example of how this is used.

Take the following function:

func addValues(a int, b int) (string, int) {
    var status string
    var result int
    if a >= 0 && b >= 0 {
        status = "OK"
        result = (a + b)
    } else {
        status = "ERROR"
        result = 0
    }
    return status, result
}

So it is called "addValues", takes two parameters that are integers and returns a string and an integer.

Inside, you can see how an if-else statement is structured in Go. In this case, it checks that both numbers are greater than 0. If they are, it sets the status as "OK" and adds the numbers. Otherwise it sets it to "Error".

You can see at the very end, it returns both the status and the result, thus satisfying the "string, int" return type.

To use it, you do something like this:

status, sum := addValues(5, 2)

The := notation is a short hand for declaring the variable and assigning the value (something that would normally have to be done separately). You will also notice that there are no types. This is because Go can infer types which means they are not strictly necessary to specify.

The return values would be assigned to each variable in the same order that you return them.

So if I modify the whole main function and run it:

func main() {
    fmt.Println(generateOutput("Antony"))
    status, sum := addValues(5, 2)
    fmt.Println(status)
    fmt.Println(sum)
    status2, sum2 := addValues(5, -2)
    fmt.Println(status2)
    fmt.Println(sum2)
}

Results in:

The final thing that I want to show is variadic parameters. These are special parameters that can be of any size.

For example, we can change addValues to look like this:

func addValues(vals ...int) (string, int) {

The ...int says that vals is a list of integers that is either empty or any size. So we can make the function work as it did before with 2 parameters and with any number of parameters:

func addValues(vals ...int) (string, int) {
    var status string
    var result int
    for _, val := range vals {
        if val >= 0 {
            status = "OK"
            result = result + val
        } else {
            status = "ERROR"
            result = 0
            break
        }
    }
    return status, result
}

You can see inside, the syntax of a for loop:

for _, val := range vals

range is a key word that is basically loading vals into the loop. val becomes the current item of the loop. _, could be replaced with a variable that is the key of the current item in the loop, but as we are not using the key, we use this special character to kind of ignore it. Go would throw a warning if we specified a variable here and did not use it.

So I add another use case in the main function (as I said, the other two cases should work as normal):

func main() {
    fmt.Println(generateOutput("Antony"))
    status, sum := addValues(5, 2)
    fmt.Println(status)
    fmt.Println(sum)
    status2, sum2 := addValues(5, -2)
    fmt.Println(status2)
    fmt.Println(sum2)
    status3, sum3 := addValues(5, 2, 3, 4)
    fmt.Println(status3)
    fmt.Println(sum3)
}

Which outputs:

I hope this guide has been useful in helping you get to grips with some basic concepts in Go!


© 2012-2017