Run Your First Function in Go
Scenario
Save the example as booking.go and run go run booking.go.
// booking.go
package main
import "fmt"
func canBook(freeSeats int) bool {
return freeSeats > 0
}
func main() {
if !canBook(1) || canBook(0) {
panic("booking rule failed")
}
fmt.Println("OK")
}
// go run booking.goTry it yourself
Predict the two return values before the program checks them.
| Case | Result |
|---|---|
| canBook(1) | Select a choice above to see what happens. |
| canBook(0) | Select a choice above to see what happens. |
Reveal the explanation
- canBook(1)
Returns true. The first failure condition is false.
- canBook(0)
Returns false. The second failure condition is false.
Since neither failure condition is true, main prints OK. Try passing text where an integer is required and read the error.
Shared booking contract
Accept a booking when at least one seat is free.
| Free seats | Expected |
|---|---|
| 0 | false |
| 1 | true |
| 2 | true |
Download shared test cases
Your turn
Run the Go contract. Then write down the input and return types from the function signature.
Common mistake Passing a string where the function expects an int.
Check your work
Three cases pass. The signature accepts an int and returns a bool.
This browser could not save your progress. Changes last until you leave the page.