Magic Boxes (func)
Grouping repeated code and giving it a name is called a function.
In Go, we use the word func.
Create a function
func sayHello() {
fmt.Println("Hi!")
}
func main() {
sayHello() // use the box
}
Ingredients and results
Go is strict: you must specify the type of each input and output.
func add(a int, b int) int {
return a + b
}
func main() {
result := add(10, 20)
fmt.Println(result)
}
Translation:
Define a magic box called add:
(inputs are numbers a and b)
(output is a number)
{
return a + b
}
Go’s special power: multiple returns
Go’s magic box can return multiple results at once.
func swap(a string, b string) (string, string) {
return b, a
}
Put in two ingredients, and two swapped results pop out.
That clarity and power is one of Go’s biggest strengths.