Go, like all modern languages, has functions. As we saw in the example where we built our first program in Go, functions start with the func
keyword.
To create a basic function that doesn’t take any parameters and doesn’t return a value, is simple:
// general form
func functionName() {
// content
}
If you want to pass parameters you put them in the parenthesis like you normally would. As with defining variables in Go, you will put the data type after the variable.
func printNameAndAge(age int, name string) {
fmt.Println("Hello",name,"you are",age,"years old.")
}
If you have multiple parameters with the same data type, you only have to put in the last data type, and it applies it to the parameters before hand.
func calculateArea(length,width int) {
area := length * width
fmt.Println("The size of the rectangle is:",area)
}
If you want return a value (since putting IO and calculations together isn’t always a good idea), then you define the return type. As with a variable definition, you put the value at the end of the function header, but before the parenthesis.
// Got to love The Hitchhikers Guide to the Universe
func answerToLifeTheUniverseAndEverything() int {
return 42
}
Note: This is a joke (or is it) from The Hitchhikers Guide to the Universe.
One interesting thing, and this is similar to some other languages, is that you do not need to store the returned value.
func main() {
answerToLifeTheUniverseAndEverything() // does not generate an error
}
Returning Multiple Variables
Originally programming functions were designed to mimic math functions, and math functions can only have a single result. However, some programming languages, like Python, and now Go, allow you to return multiple values from the function.
To create a variable that will return multiple variables, you will need to put two (or more) variables, separated by a comma where the return type is. Those variables need to be within a parenthesis like you see below.
func main() {
var num int
var text string
num, text = returnMulti()
fmt.Print("Was the answer ", num, " for ", text, "?")
}
func returnMulti() (int, string) {
return 42, "everything"
}
Notice that we need to call our function, and not put parenthesis around the returned results as well as we need to define the variables first in this example, but not always.
Here we want to simplify how we return values, so we define the names in the return types, so we don’t actually specify them as returning. You can also see how we define variables as we assign them from the returned value of the function.
func main() {
var num, text = returnMulti() // here we're setting the type based upon the return type
fmt.Print("Was the answer ", num, " for ", text, "?")
}
func returnMulti() (value int, info string) {
value = 42
info = "everything"
return // notice how we still have to call return
// if we don't call return, we'll get an error
}
Error Handling in Go
The use of multiple return types is how Go handles Errors instead of something like a try / catch block. This is because try / catch can slow down your execution of your application.
Let’s look at an example of a built in function for Go:
func Open(name string) (file *File, err error)
// when we call Open, we get to handle it like:
f, err := os.Open("sample.txt")
if err != nil {
// here we test to see if there was an error and what to do if there was
log.Fatal(err)
}
Working with an Unknown Number of Parameters
Sometimes we want to have a function be able to take a series of parameters passed to it, where we won’t know how many parameters there might even be. Think about something like the fmt.Print()
function, which takes sometimes one, and sometimes many parameters.
func sum(args ...int) int {
total := 0
for _, v := range args { // Iterate over all the args
total += v // add the values to the total
}
return total // return the total amount
}
Here we have a function called sum. The …int, lets us know there is going to be a series of integers passed to this function.
Since we don’t know how many, we use a for loop, which allows us to iterate over a collection of values. This way we can handle each one, one at a time, without knowing how many there are.
The for each type loop in Go, has a key/value pair, so we ignore the key (_) and focus on the values, adding them one to another.
// sample code for calling sum
func main() {
fmt.Println(sum(1, 3, 5)) // 9
fmt.Println(sum(2, 8)) // 10
fmt.Println(sum(3,5,7,11,13)) // 39
}
Other Things?
There are other things you can do, such as closures, and assigning a function to a variable like we’ve talked about in JavaScript, and more. However, we don’t need to worry about those things at this time, so we’ll just focus on what we have.
Creating and Using Functions in Go was originally found on Access 2 Learn