Go Functions — Roadmap
This article will cover how to create functions in Go. Functions are an essential part of any programming language.
Functions: Putting the Fun in Fundamentals
Functions are a fundamental building block of Go programming. They allow you to group a set of instructions together and give them a name, making them reusable and modular. In Go, functions are defined using the keyword `func` followed by the function name, a list of parameters, and then the function body.
```go
func functionName(param1 type1, param2 type2) returnType {
// function body
return value
}
```
Calling Functions
If you don’t use your function, which is referred to as calling a function, then you aren’t actually getting the value or benefit of creating functions. To call a function in Go you follow this syntax:
```go
func add(a int, b int) int {
return a + b
}
fmt.Println(add(8, 10)) // this will print 18 to the terminal
```
Multiple Return Types
In Go, it is also possible to return multiple values from a function. This can be done by listing the return typesseparated by commas:
```go
func multipleReturns() (int, string) {
return 42, “Hi, there”
}
```
Calling this function uses a different style than previously mentioned. In order to call this function, you can use the “multiple assignment” feature of Go to assign the returned values to separate variables:
```go
a, b := multipleReturns()
fmt.Println(a) // prints 42
fmt.Println(b) // prints Hi, there
```
Naming Multiple Returns
You can give names to the return values. This makes it a bit more readable and easier to understand the purpose of each returned value. Here’s an example:
``` go
func namedReturns() (a int, b string) {
a = 42
b = “Hi, there”
return
}
```
You can call this function in the same way as before, but now you can use the named return values instead of the order of the returned values.
```go
x, y := namedReturns()
fmt.Println(x) // prints 42
fmt.Println(y) // prints Hi, there
```
Play Around
I urge you to play around with creating your own functions. See if you can create a function that returns multple values where one of the values is an error. You might have to look up the `error` data type on the official docs for Go. We will cover the error data types and others soon.
Conclusion
Go functions are a powerful tool for writing modular and reusable code. The ability to return multiple values and give them names makes it easy to write and understand the code.