Function Basics
In this page:
Declaring a Function
A function is declared with the func keyword, a name, a parenthesized parameter list (each with a name and type), and an optional return type. The body runs whenever the function is called elsewhere in the program.
Example: Declaring a Function
package main
import "fmt"
func square(n int) int {
return n * n
}
func main() {
fmt.Println(square(6))
}
Login to try C/C++/Java/PHP code in the editor
Multiple Parameters
Functions can take several parameters, each declared with its own name and type, or grouped together when consecutive parameters share the same type to reduce repetition.
Note: Consecutive parameters sharing a type can omit the type on all but the last, e.g. 'func add(a, b int) int'.
Example: Multiple Parameters
package main
import "fmt"
func rectangleArea(width, height float64) float64 {
return width * height
}
func main() {
fmt.Println(rectangleArea(4.5, 3.0))
}
Login to try C/C++/Java/PHP code in the editor
Functions with No Return Value
A function that doesn't need to hand back a result simply omits the return type, and inside its body a bare return (or reaching the end of the function) exits it.
Example: Functions with No Return Value
package main
import "fmt"
func logMessage(msg string) {
fmt.Println("[LOG]", msg)
}
func main() {
logMessage("server started")
}
Login to try C/C++/Java/PHP code in the editor
Every Path Must Return
If a function's signature declares a return type, the Go compiler requires that every possible execution path through the function ends in a return statement -- an if without a matching else that also returns won't compile.
Example: Every Path Must Return
package main
import "fmt"
func sign(n int) string {
if n > 0 {
return "positive"
} else if n < 0 {
return "negative"
}
return "zero"
}
func main() {
fmt.Println(sign(-5))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting that Go requires the parameter type after each name, and that consecutive same-typed parameters can share one type annotation.
- Trying to call a function before it's declared in the file -- unnecessary in Go, since order of top-level declarations doesn't matter, unlike some scripting languages.
- Not returning a value on every code path when the function signature declares a return type, which is a compile error.
- Functions are declared with 'func name(params) returnType { }'.
- Parameters of the same type can share a single type annotation.
- Every code path in a function with a declared return type must return a value.
- Top-level function order in a file doesn't matter -- Go resolves all declarations before running.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: