A function in Go (Golang) is a reusable block of code that performs a specific task.
Functions are a fundamental part of the programs we write. They can be defined and invoked like in many other programming languages, and they also promote modularity and readability of our code. In this post, we’ll take a close look at functions and explore some of the ways in which they can be used.
Syntax
Here’s the signature of a function:
func <name>(<parameters>) <return type> {
// Body of the function
}
Functions declarations begin with the func
keyword, followed by a name for function, then any comma-separated parameters, then the data type of the function’s return value (if any).
Within the body of the function, we can include any custom logic we want. Note that by convention, function bodies should remain relatively short and “just do one thing.”
Here’s an example of a function that takes two integers as input and returns their sum:
package main
import "fmt"
func sum(x, y int) int {
return x + y
}
func main() {
fmt.Println(sum(41, 10)) // Output: 51
}
In the example above, the function sum
accepts two parameters from the user: x
and y
, both of which are of type int
. Then, when x + y
is evaluated, the function returns a value of type int
.
Note that we also defined a main
function, a function with no parameters and no return value. This function serves as the “entry point” of a Go program. That is, the main
function is what gets executed when you run a Go program. As such, when the program above is run, the main
function invokes sum(41, 10)
and prints 51
to the console.
Functions can have no parameters
Note that while functions can accept any number of parameters (as seen with the sum
function), having any input parameters at all is entirely optional (as we’ve seen with the main
function).
Functions without parameters are useful for cases in which you want to perform specific tasks that do not require any external input, or when inputs can be determined automatically by the function itself. For example, you might write a function to get the current time:
package main
import (
"fmt"
"time"
)
func getCurrentTime() {
time := time.Now()
fmt.Println("The current time is: ", time)
}
func main() {
getCurrentTime()
}
You might also write a function that simply prints a fixed message:
package main
import "fmt"
func greeting() {
fmt.Println("Hello world!")
}
func main() {
greeting()
}
In each of these examples, the function name is followed by empty parentheses, indicating that the function does not take any parameters.
Functions can have multiple return values
In the examples above, we’ve seen functions with zero return values (i.e., getCurrentTime
and greeting
) as well as a function with a single return value (i.e., sum
). Go also has built-in support for a function to have multiple return values. Consider the following example:
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("divided by zero")
}
return a / b, nil
}
func main() {
fmt.Println(divide(8, 2))
fmt.Println(divide(10, 0))
}
Here, the function divide
accepts two float64
values as input: a
and b
. As a result of the operations in the function body, the function returns two values: the result of the division, as well as an error (if the second parameter is zero). As such, when divide(8, 2)
is evaluated, we see 4 <nil>
printed to the console. And when divide(10, 0)
is evaluated, we see 0 divided by zero
.
By returning multiple values, functions can provide more information and context to the user invoking the function, which can help with error handling and data processing.
Learn more about functions
Functions are a powerful feature of the Go programming language. They allow developers to encapsulate logic, define any input parameters from the user, and return many values. Functions are an essential feature for any programming language, and Go provides a robust and flexible implementation. For more information about functions and how to leverage them in the Go programs you write, enroll in Udacity’s Golang course.