We can pass values into a function with arguments. We can also use a return statement to send a value back out of a function.
In Go, a function that returns a value declares the return type after the parameter list:
func plusThree(num int) int {
return num + 3
}
When execution reaches return, the function stops and sends the value back to the calling code:
func plusThree(num int) int {
return num + 3
}
func mainFunction() {
answer := plusThree(5)
fmt.Println(answer) // Output: 8
}
Using a returned value
The returned value can be stored in a variable, printed, or used in another expression.
func getMessage(name string, language string) string {
return "Hey, " + name + "! Welcome to " + language + "!"
}
func mainFunction() {
message := getMessage("Andy", "Java")
fmt.Println(message)
}
No return statement
In Go, if a function declares a return type, it must return a value of that type. A function declared with string must return a string, and a function declared with int must return an integer.
Multiple returns & error handling:
Unlike most languages, a Go function can return several values at once. The common idiom is to return a result and an error, then check the error before using the result.
func half(n int) (int, error) {
if n%2 != 0 {
return 0, fmt.Errorf("odd number")
}
return n / 2, nil
}
v, err := half(10)
if err != nil {
// handle the error
}
fmt.Println(v) // 5
That v, err := f() followed by if err != nil pattern appears all over the coding tutorials — it's how Go reports failures instead of throwing exceptions.
Assignment
Follow the Coding Tutorial and let's write a function that returns a value.
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
