Go · Chapter 24 of 26

Generics

By the end of this chapter you can write one function or one type that works for many types: give it type parameters, say what those types must allow with a constraint (any, comparable, cmp.Ordered, or your own union with ~), build a generic type with methods, range over a function with iter.Seq, and tell when a type parameter is the right tool and when an interface is. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Services
  • 4 tasks
  • Go
  • In the all labs plan

The first 2 chapters of Go are free. This one comes with the all labs plan.

Why you need this

BijliGo's code is full of loops that differ only in their types. Pooja adds up energy in int watt-hours, power in float64 kilowatts and money in paise. Tenzin keeps a cache of chargers, another of statuses and another of station names, and his three "group the rows by" functions are the same loop three times. Here are two from the status service:

func maxInt(a, b int) int {
	if a > b {
		return a
	}
	return b
}

func maxFloat(a, b float64) float64 {
	if a > b {
		return a
	}
	return b
}
11700 60

Every copy is one more place for a bug to be fixed in one and not the others. The Go you know offers two ways out, and both cost something. Copy the code for every type, as above. Or take any (chapter 9) and assert the type inside:

func largerAny(a, b any) any {
	if a.(int) > b.(int) {
		return a
	}
	return b
}
11700
panic: interface conversion: interface {} is float64, not int

The compiler accepted largerAny(7.4, 60.0) and the program crashed at run time, and every caller gets back an any it must assert again. Generics give you one copy of the code that the compiler still checks for every type it is used with.

What you build: 4 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    sum.go: one SumBy for every kind of number

    In sum.go, write the constraint Number and the function SumByT any, N Number N) N, which adds up value(item) for every item and returns the total (0 for no items).

    Number must allow int, int64 and float64, and every type built on them: the Check's own type chkPaise int must satisfy it. As given, Number allows no types in particular, so Go will not let you add two values of type N.

    The Check adds the energy of all 3600 sessions as ints (44632024), the power of all 1180 chargers as float64s (22112.7, give or take 0.001), the cost of all sessions as chkPaise (83158805), all 2000 wallets as int64s (198681000), and no sessions (0).

  2. Task 2

    top.go: the top N of anything

    In top.go, write TopNT any, K cmp.Ordered K) []T. It returns the n items with the largest key, largest first; items with equal keys keep the order they had in items. n larger than len(items) returns all of them, sorted; n of 0 returns none. The caller's slice must not change.

    The Check asks for the top 3 sessions by EnergyWh (S900763, S903400, S900322: the first two both used 35515 Wh), the top 5 drivers by WalletPaise (D10539, D10615, D11364, D11495, D10290), the top 4 chargers by PowerKW (C1001, C1002, C1017, C1021), the top 2 stations by Name (ST129, ST037), all 4 tariffs with n of 10 (DC60, DC30, AC7, LEV3) and 0 tariffs, and checks the sessions' order after the call.

  3. Task 3

    cache.go: a cache for any key and any value

    In cache.go, write the generic type Cache[K comparable, V any] and its functions: NewCacheK, V *Cache[K, V] returns an empty cache; Set(key K, value V) stores value under key, replacing any old one; Get(key K) (V, bool) returns the value and true, or V's zero value and false; Len() int returns how many keys it holds. Add the fields you need to the struct.

    The Check uses a Cache[string, bijli.Status] (Get on an empty cache, Set, Get, Set again with another State, Len 1) and a Cache[int, string] that 50 goroutines use at once (each Sets its own key, Gets and calls Len), under the race detector; afterwards Len is 50 and Get(9) is "ST010".

  4. Task 4 · interview question

    Interview: groupby.go, one GroupBy for every row

    Tenzin has ChargersByKind, DriversByVehicle and StationsByHost: the same loop three times. In groupby.go, write GroupByT any, K comparable K) map[K][]T once: every item goes into the group of its key, and each group keeps the items in their order.

    The Check groups the chargers by Kind (AC7 339, DC30 316, DC60 148, LEV3 377, each group in id order, DC60 starting with C1001), the drivers by Vehicle (car 1112, auto 526, scooter 362), the sessions by a struct of station and status ({ST001 completed}), and no tariffs (an empty map).

    Joseph will ask: generics or interfaces? When does a type parameter help, and when is an interface the better tool?

What you will learn

  • Type parameters: func LargerT cmp.Ordered T, one function for many types.
  • Constraints: any, comparable, cmp.Ordered, and your own unions such as ~int | ~float64.
  • Inference: Go works out T from the arguments; Largerfloat64 says it yourself.
  • Generic types: Set[T comparable], a struct with type parameters, and its methods.
  • iter.Seq: a function you can range over.
  • Generics or interfaces: one type at a time, or many types mixed.

More in Services

Build "Generics" yourself

BijliGo, a Bengaluru EV charging network, drops chargers at the evening peak. You rewrite its backend in Go. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Go are free. This one comes with the all labs plan.