Curriculum

Curriculum

Run Your First Function in Go

Scenario

Save the example as booking.go and run go run booking.go.

Selected choicePick a choice below
Result—
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.go

Try it yourself

Predict the two return values before the program checks them.

Reveal the explanation
  1. canBook(1)

    Returns true. The first failure condition is false.

  2. 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.

Read free seats
Is the count greater than zero?
Yes
Accept
No
Decline
Free seatsExpected
0false
1true
2true
Runnable reference files
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.