Practice: write your first Go program

A short warm-up with no repo tests: a small program with a struct, a method, a map, a function with two return values, an error and a defer.

Objective

Build a small rate-limiter-flavoured Go program that combines the language features from lessons 1.4 to 1.7. This optional warm-up gives you a chance to use functions, structs, methods, interfaces, maps, control flow, and error handling together before moving on to the rate limiter exercises.

By the end:

  • A Counter tracks how many times each user has been seen.
  • A CountingGate implements a Gate interface and allows users up to a configured limit.
  • Invalid input returns an error that the caller handles immediately.
  • The program prints each decision and a summary in first-seen user order.
  • defer prints done as the final line.

This exercise is optional. It does not block the week, is not part of the zomato-prep repository, and has no repository tests.

Deliverables

  • ~/warmup/main.go: A standalone Go program with package main containing:

    • A Counter struct with a map[string]int.
    • A NewCounter constructor returning *Counter.
    • An Add method that increments a user's count or returns an error.
    • A Count method that returns the current count for a user.
    • A Gate interface with an Allow method.
    • A CountingGate struct with a limit and a counter.
    • An Allow method that delegates counting to Counter.Add.
    • A main function that exercises the gate, handles errors, prints decisions, and displays the summary.

    Required signatures:

    go
    type Counter struct {
        counts map[string]int
    }
    
    func NewCounter() *Counter
    
    func (c *Counter) Add(user string) (int, error)
    
    func (c *Counter) Count(user string) int
    
    type Gate interface {
        Allow(user string) (bool, error)
    }
    
    type CountingGate struct {
        limit   int
        counter *Counter
    }
    
    func (g *CountingGate) Allow(user string) (bool, error)

Requirements

Constraints

  • Work in a scratch folder outside the zomato-prep repository. Create it and initialize a separate Go module:

    bash
    mkdir -p ~/warmup
    cd ~/warmup
    go mod init warmup
  • Use only the Go standard library. You need fmt for output and errors for constructing the empty-user error.

  • Implement Counter with a map from user names to integer counts. Initialize the map in NewCounter.

  • In Counter.Add, return an error with the exact text empty user when the supplied user is an empty string. Otherwise increment the count and return the new value.

  • Implement Counter.Count(user string) int to read a user's count from the map.

  • Declare Gate with Allow(user string) (bool, error).

  • Implement CountingGate with:

    • limit int
    • counter *Counter
  • CountingGate.Allow must call Counter.Add, pass any error back to its caller, and report whether the resulting count is less than or equal to the configured limit.

  • In main, create a CountingGate with a limit of 2. Store it in a variable whose declared type is Gate, not *CountingGate.

  • Process this exact input slice using for range:

    go
    []string{"asha", "bo", "asha", "asha", "", "bo"}
  • For each user:

    • Print <user>: allowed when the gate allows the request.
    • Print <user>: rejected when the gate rejects the request.
    • If Allow returns an error, print error: empty user and use continue to skip the remaining processing for that input.
  • Keep a separate slice of first-seen users for the summary. Add a user to it only the first time that user appears. Do not rely on map iteration order.

  • Print the summary in first-seen order using Counter.Count to retrieve the counts.

  • Call defer fmt.Println("done") near the beginning of main.

  • Do not use global variables.

  • Check every returned error immediately in the caller.

  • Use pointer receivers for methods that mutate their receiver.

  • Format the file with gofmt.

Acceptance criteria

  • Expected output: Running go run . prints exactly these eight lines, in this order:

    asha: allowed
    bo: allowed
    asha: allowed
    asha: rejected
    error: empty user
    bo: allowed
    summary: asha=3 bo=2
    done
  • Interface usage: The gate is stored in a variable declared as Gate, and the program calls Allow through that interface value.

  • Error handling: The empty user produces error: empty user. The error is checked and handled without terminating the program.

  • Summary ordering: The summary always lists asha before bo, based on first appearance rather than map iteration.

  • Formatting and vetting: go vet ./... reports no issues, and gofmt -l . prints nothing.

  • Run locally: From the scratch folder, execute:

    bash
    go run .
    go vet ./...
    gofmt -l .

    There is no make command for this exercise because it has no repository test target and is deliberately completed outside zomato-prep. The repository command make test W=... does not apply.

Finished Exercise 1.8?

Go fundamentals

5 items

  • 1.4Go basics: types, functions and defernot completed
  • 1.5Structs, pointers, slices and mapsnot completed
  • 1.6Methods and receiversnot completed
  • 1.7Interfaces and Go errorsnot completed
  • 1.8Practice: write your first Go programnot completed

Rate limiting and token bucket algorithms

Up next · Module 3 · 3 items · about 2 h 45 min

Start module 3

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. The program runs with go run ..
  2. It defines a struct and a method on it.
  3. It stores and reads values in a map and uses the comma-ok form.
  4. It has a function that returns a value and an error, and the caller checks the error.
  5. It uses defer to print a closing message.

Commands

terminal
mkdir -p /tmp/warmup && cd /tmp/warmup && go mod init warmup
terminal
cd /tmp/warmup && go run .

This exercise has no Go test. The commands above are the check: when each one shows what the list says, the exercise is done.