My today’s subject is functions.
Functions are the core of programming in Go.
We can declare our own functions and call them in every place in the package.
Usually, the name of the function starts in lower case but the function which name starts in a capital letter can be used outside the package.
Each function can take zero or more arguments.
If our function takes arguments we have to declare their types. We write the name of a parameter and its type in parenthesis just after the function name. If we want to pass more than one argument we need to separate each declaration with a coma.
func sum(a int, b int) {
fmt.Println(a + b)
}
If the arguments are the same type, we can add the type to
the last one only. func sum(a, b int)
it means that both
parameters’ type is the same.
4.
Now, we can call our function inside the main() function.
We can’t forget about passing the arguments (of course, if
the function requires any).
package main
import “fmt”
func main() {
sum(5, 7)
}
func sum(a int, b int) {
fmt.Println(a + b)
}
- If we want to be able to use the output of our function, we need to return something. A function that only prints the results doesn’t “last long”. In the example above, the function only prints the sum of two numbers but then, the result is removed. Our sum function could be very helpful if we would like to build a simple calculator but only when we add a return statement. One more thing. We already declared the types of arguments that our function takes, now we also have to declare the type of the value the function returns. We are adding it after the brackets with parameters. Let’s add those two elements to our sum function:
func sum (a, b int) int {
return a + b
}
- Functions can return more than one value, so we have to declare all those values. Then we put them all into another pair of brackets. Let’s look at the divide function. Working on our calculator we should remember that it’s not possible to divide by zero. We have to handle such a case.
func divide(a, b float64) (float64, error) {
if b == 0.0 {
return 0, errors.New(“You can’t divide by zero”) //1
}
return a / b, nil //2
}
Now, as we declared that our function will return two values, we have to have those two values in every return statement. That’s why in the first if block (1) we have two elements one of them can be zero and the other will be the information about the error.
If argument b is not equal to zero, the next block (2) will be executed. Here we also need to return 2 values: the result of the division and nil. Nil informs us that there are no mistakes in our function.
I think those are the very basics of functions in Go.
(If you can see that numbers of li elements are weird - like a bunch of 1 - I don't know how to fix it here)
Top comments (1)
Thank you, Michael.
I was wondering if devs often use those naked functions.