Functions are a great way to organize code into packages, or DRY up a single package.
A gentle introduction:
package main
import "fmt"
func main() {
sayHi()
sayHi()
}
func sayHi() {
fmt.Println("hi")
}
functions start with the func
keyword, are given a name, parenthesis, and then given a block of code. Similar to variables, if functions are capitalized they are exported from the package.
Functions can also take arguments:
package main
import "fmt"
func main() {
sayHi("Larry Sanders")
}
func sayHi(name string) {
fmt.Println("Hey now,", name)
}
Here we can see the identifier ("name") comes first, and the type ("string") follows.
You can also have multiple arguments separated by commas:
func sayHi(name string, dayOfWeek int) {
fmt.Println("hey", name, dayOfWeek - 5, "days to go.")
}
If there are types in a row that are the same, you can remove all but the last type:
func sayHi(firstName, middleName, lastName string, dayOfWeek int) {
...
}
Functions also can have return values:
package main
import "fmt"
func main() {
fmt.Println(divide(1, 2))
}
func divide(a, b int) int {
return a / b
}
Functions also can have multiple return values. Generally the second return value is an error type.
package main
import (
"fmt"
"errors"
)
func main() {
ans, err := divide(1, 0)
if err != nil {
fmt.Println(ans)
}
}
func divide(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("Divide by zero!")
}
return a / b, nil
}
We look at errors and conditionals in more detail in section 2.4.
They can even have named return values so you don't have to explicitly return values.
...
func divide(a, b int) (answer int, e error) {
if b == 0 {
e = errors.New("Divide by zero!")
return
}
answer = a / b
return
}
Functions are first class citizens in go - they are a kind of type
. That means you can create anonymous functions inside functions:
package main
import "fmt"
func main() {
// An anonymous function that is immediately invoked
func(a, b int) {
fmt.Println(a+b)
}(10, 11) // this is how it is immediately invoked
// Assigning a variable to an anonymous function
myFunc := func(a, b int) {
fmt.Println(a+b)
}
myFunc(1, 2)
myFunc(3, 4)
// An anonymous func with a return value
add := func(a, b int) int {
return a + b
}
ans := add(1, 2)
fmt.Println(ans)
// You can also create closures
word := "hello"
printWord := func() {
fmt.Println(word)
}
printWord()
}
Functions are first class citizens (they are types). Create a function that takes a function as a parameter, and calls it. Create a function that returns a function.
- Functions can return more than two values, but rarely do. Instead, you probably want to break your function into smaller pieces.
Here's an article if you're having trouble with higher order functions.