Declare and call functions
Declare and call functions
A function is a named or anonymous block of reusable behavior. A package-level declaration begins with func, followed by its name, parameter list and body. Calling the function with parentheses transfers control to its body; when it finishes, execution continues at the call site.
package main
import "fmt"
func greet() { fmt.Println("Hello") }func main() { greet() greet()}The declaration does not print by itself. Each call runs the body once. main is the entry function; ordinary named functions can be declared before or after it at package scope.
Compose small functions
package main
import "fmt"
func header() { fmt.Println("Report") }func footer() { fmt.Println("End") }func main() { header() fmt.Println(42) footer()}Function names describe intent. Do not write a named function declaration inside main; Go permits anonymous function literals there, introduced later in this chapter. A function without results cannot be assigned to a variable by calling it.
Try it locally
Declare line to print ---. Call it before and after printing Menu. Expected lines: ---, Menu, ---.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 01: Declare and call functions
Check the lesson objective before moving on.
What executes a declared function body?
Where can an ordinary named function be declared?