Golang in sixty seconds — function basics
In any programming language a function can often be thought of as a black box that will perform an action. They can take inputs and return outputs, but they don’t have to do either. They’re most often used to separate code to aid readability and understanding, and to avoid repetition.
In Go, a function looks like this:
func add(num1 int, num2 int) int {
return num1 + num2
}
Functions always start with the keyword func
followed by the function name (add
). The parameters (inputs) of the function are defined name type, name type
. You can have as many parameters as you like separated by commas, however I would recommend having as few as possible. After the parameters we need to put the return type (int
) followed by some curly braces. The curly braces defines the scope of the function, and inside is where the function will do it’s work (in our case adding our two inputs).
We would call our function like this:
result := add(13, 29)
fmt.printLn(result) // 42
Here we’re assigning the returned value to a variable result and then using the built in printLn function to print it to the console.
There’s much more to learn about functions, so please take a look at the other Golang in sixty seconds articles.
Get Unlimited access to Medium
Buy me a coffee if you enjoyed the article :)