golang

Golang Func

Functions are essential in the go programming language. In a nutshell, a function is a block of code in a program that allows developers to reuse a piece of code more than once in a program. Once you define a function, you can selectively re-use the piece of code in other parts of the program without redefining the code.

Functions are very useful when you need to save memory and improve the readability of your code. This is because functions help to organize code in modular sections, enhancing readability.

This guide will teach you how to work with functions in the go programming language. This will help you understand how you can define your own functions in your programs.

The Basics

As mentioned, a function is a piece of code or statements that perform a specific task. Go comes with a collection of pre-defined functions from its standard library.

An example of a popular function is the fmt.Println() function.

Let us understand how we can create custom functions in Go.

Go Define Function

Start by creating a folder called functions and navigate into it.

$ mkdir functions
$ cd functions/

Create a file “functions.go” to store the source code:

$ touch functions.go

To define a function in go, we start with the keyword func. It’s then followed by the name of the function and a pair of parentheses. If a function accepts parameters, you can pass them inside the parentheses. Keep in mind that a function can have no parameters.

Finally, create the function block (what the function does) inside a pair of curly braces.

The general syntax for function definition is as shown:

func function_name(params) {
    // function block
}

Let us create a function called greet:

func greet()

The code above will act like the definition of our function.

Next, we will create a function block that contains the code of what operation the function executes.

func greet() {
    fmt.Println("Hi, everyone!")
}

Here, the function prints the string “Hi, everyone!” to the console.

Now that our function is defined and complete, we need to make sure it performs the set task.

Go Call Function

For the function to perform the defined actions, we need to call it. In go, the execution starts at the main function. Hence, we need to call our greet() function inside the main function.

Consider the example code below:

package main

import "fmt"

func main() {
    greet()
}

func greet() {
    fmt.Println("Hi, everyone!")
}

Now we can run our program as:

$ go run functions.go

Once we run the program, we should see the output of the greet() function as:

::output
Hi, everyone!

NOTE: In go, the main function tells the compiler where the program execution starts. You can only have one main function in a program, and it does not accept any arguments or return any value.

Functions can be more complex than the one we used above. You can use other features of golang such as loops, nested functions, conditional statements, and more.

For example, the function below uses two variables to compare the max value.

package main
import "fmt"
func main() {
    max()
}
func max() {
    var var1 = 10
    var var2 = 100
    var maximum = 0;
    if var1 > var2 {
        maximum = var1
    } else {maximum = var2}
    fmt.Println(maximum)
}

In the above example, we define a function called max. We then define 3 variables and compare if var1 is greater than var2. If true, we set the maximum value to 1; else, set the maximum value to var2.

Next, we print the value of the maximum variable using the Println method. Once we call the max() function, we should see the largest value as:

$ go run functions.go
100

Go Function Parameters

We mentioned you can create parameters for your functions. Let us look at how we can create functions with parameters.

A parameter refers to a defined unit that acts as an argument that a function can accept.

To define parameters in a function, pass them inside the parentheses during the function definition.

In go, we start by the name of the parameter and its data type. The syntax for defining a function with parameters is as shown:

func function_name(param1 data_type, param2 data_type) {
    // function body
}

Let us re-think the max function and see how we can include parameters to make the function more flexible.

We can define two parameters that act as the two values to compare. This allows the user to pass any custom values during the function call.

The resulting function is as shown:

func max(a int, b int) {
    var maximum = 0
    if a > b {
        maximum = a
    } else {
        maximum = b
    }
    fmt.Println(maximum)
}

In this example, the max function takes two values, compares them, and returns the highest. In the main function, we can call the max() function as:

func main() {
    max(100,20)
}

Notice that we can pass custom values than manually hard-coding them inside the function.

HINT: If you have a set of parameters of the same type, you can skip setting the data type for each and simply set it as one type.

For example, since the parameters of the max functions are int, we can define them as:

 func max(a, b int) {
  // function body
}

Go Functions Return Value

If a function can accept a value, it certainly can return one. In golang, we can return a value from a function using the return keyword. When the compiler encounters the return keyword, it exits the functions and returns to the caller function.

You must specify the data type of the return value during function declaration. The syntax is as shown:

func function_name(params data_type) return_value_data_type {
    // function body
}

Let us modify the max function to return the maximum value instead of printing it using the Println function.

func max(a, b int) int {
    var maximum = 0
    if a > b {
        maximum = a
    } else {
        maximum = b
    }
    return maximum
}

In the example above, you notice we add a return type of int in the function declaration. We then use the return keyword to return the value of the maximum variable.

Since the function returns a value, we can pass that value to other functions as shown in the example below:

func main() {
    // greet()
    // max(100,20)
    fmt.Println("The max value: ", max(250, 188))
}

The example uses the return value of the max function and passes it to the Println function.

Go also allows you to return multiple values from a function. For example, we can return a string and int from the same function as shown:

func max(a, b int) (int, string) {
  // function body
  return maximum, "a string return type"
}

In the example above, we return an int and string value.

Conclusion

This guide explored how to work with functions in the go programming language. Keep practicing to become a better programmer.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list