Go — Functions with typed parameters
A Go function declares parameter types and a result type. Return the calculated value so the caller can use it with different quantities and capacities.
A simple example
Call a function with 2
- Start with Argument 2
- Do this Double the argument
- Result 4
package main
import "fmt"
func twice(n int) int {
return n + n
}
func main() {
fmt.Println(twice(2))
}
4
Calculate how many boxes an order needs
The parameters share the declared type int. The function returns a value directly, so main can call it with different inputs. Integer division and remainder distinguish a full box from a partial box.
A library ships 17 books in cartons that hold eight. Two cartons take sixteen books, leaving one book that still needs a carton. An order of exactly sixteen needs only two.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func boxesNeeded(items, capacity int) int {
full := items / capacity
if items%capacity != 0 {
full++
}
return full
}
func main() {
fmt.Println(boxesNeeded(17, 8))
fmt.Println(boxesNeeded(16, 8))
}
3 2
The input contract is a nonnegative whole-number item count and a positive box capacity. Seventeen items fill two boxes of eight with one item left over. Sixteen items fill exactly two boxes.
Try it yourself
How many boxes do zero items need?
Check your answer
Zero. The quotient and remainder are both zero. A zero capacity is outside the function’s contract because division by zero is undefined.