Use parameters and results
Use parameters and results
A parameter is a local input variable declared in the function signature. An argument is the value supplied at the call. A result type after the parameter list describes what the function returns. Use return to send a value back to the caller.
package main
import "fmt"
func double(n int) int { return n * 2 }func main() { fmt.Println(double(6))}The argument 6 initializes n, and return produces 12. The caller decides what to do with that value. Printing inside a function is not the same as returning a value.
Combine parameters
package main
import "fmt"
func cost(price, quantity int) int { return price * quantity }func main() { total := cost(7, 3) fmt.Println(total + 2)}Both parameters have type int. price, quantity int abbreviates two declarations of the same type. Supply arguments in order and with assignable types. A function with results must end its body with a terminating statement, such as a return or an if whose branches both return. A missing return is a compile error.
Try it locally
Write rectangle(width, height int) int returning the area. Print results for (3, 5) and (0, 4).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 02: Use parameters and results
Check the lesson objective before moving on.
What is n in func double(n int) int?
What does return n*2 do?