Go Functions
A function is a named block of code that does one job. A call runs that block at the place of the call.
A function that prints
The greet function holds one print line. Main calls greet by name.
package main
import "fmt"
func greet() {
fmt.Println("Hello")
}
func main() {
greet()
}A parameter and a return
The add function takes two int parameters. It returns their sum to the caller.
package main
import "fmt"
func add(a int, b int) int {
return a + b
}
func main() {
fmt.Println(add(4, 5))
}A variadic parameter
Three dots before the type make a parameter variadic. The function can take two values in one call and three in the next.
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(sum(1, 2, 3))
fmt.Println(sum(2, 3, 4))
}Two functions called in order
Each call runs its own function. The lines print in call order.
package main
import "fmt"
func start() {
fmt.Println("Start")
}
func finish() {
fmt.Println("Finish")
}
func main() {
start()
finish()
}Example
package main
import "fmt"
func printItem(name string, price int) {
fmt.Println(name+":", price)
}
func totalPrice(a int, b int) int {
return a + b
}
func main() {
printItem("Pen", 3)
printItem("Book", 12)
fmt.Println("Total:", totalPrice(3, 12))
}Key points
- Use the func keyword to define a function.
- A parameter is a named input that a call fills with a value.
- The return type follows the parentheses when a function sends one value back.
- Use return to send a value back to the caller.
- A variadic parameter accepts any number of values of one type.
In this example, printItem prints one labelled line for each item. The totalPrice function returns the sum of the two prices. Main prints that sum beside the word Total.
Note
main is a function too, and the program starts by running it.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does the ...int in func sum(nums ...int) int mean?