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 keywordfunc
followed by the function name (add
). The parameters (inputs) of the function are definedname 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.
Self taught software developer with 11 years experience excelling at JavaScript/Typescript, React, Node and AWS.
I love learning and teaching and have mentored several junior developers over my career. I find teaching is one of the best ways to solidify your own learning, so in the past few years I've been maintaining a technical blog where I write about some things that I've been learning.
I'm passionate about building a teams culture and processes to make it efficient and satisfying to work in. In many roles I have improved the quality and reliability of the code base by introducing or improving the continuous integration pipeline to include quality gates.