ข้ามไปยังเนื้อหา

บทเรียนที่ 22 · Objects and Generics

Generics and Concepts in Nim

Learn generic procs and types in Nim, how type parameters are instantiated at compile time, constraints, and concepts, with a C stand-in showing monomorphization.

A function that finds the larger of two numbers should not care whether they are int or float. Generics let you write that once with a placeholder type and have the compiler produce a specialized version for each type you use. Nim generics are checked and instantiated at compile time, so there is no run-time cost.

The Nim code is read-only on this site; the C stand-ins model what the compiler produces.

Generic procs

Put the type parameters in square brackets after the name.

NIM
proc biggest[T](a, b: T): T =
  if a > b: a else: b

echo biggest(3, 9)         # 9
echo biggest(2.5, 1.0)     # 2.5
echo biggest("pear", "fig")  # pear

Nim infers T from the arguments. The body is only checked when it is instantiated: biggest works for any type that has >, and calling it with a type that lacks > gives a compile error pointing at the call.

Generic types

Types can have parameters too, which is how seq[int] and Table[string, int] are defined.

NIM
type
  Stack[T] = object
    items: seq[T]

proc push[T](s: var Stack[T], x: T) = s.items.add x
proc pop[T](s: var Stack[T]): T = s.items.pop()
proc len[T](s: Stack[T]): int = s.items.len

var s: Stack[string]
s.push "a"
s.push "b"
echo s.pop()      # b

Monomorphization

For every distinct type argument the compiler writes a separate copy of the code, a process called monomorphization (the same strategy as C++ templates and Rust generics). The stand-in uses a C macro to stamp out two versions by hand.

C C stand-in: one definition, two instantiations

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The upside is speed: each copy is optimized for its type. The downside is larger binaries when you instantiate many types.

Constraints

You can restrict T in the signature. A constraint is any type class: a concrete type, a union, or a built-in class such as SomeNumber.

NIM
proc total[T: SomeNumber](xs: openArray[T]): T =
  for x in xs: result += x

echo total([1, 2, 3])        # 6
# echo total(["a", "b"])     # compile error: string is not SomeNumber

Other useful classes are SomeInteger, SomeFloat, Ordinal and typedesc. The when and compiles checks in Compile-Time Execution let you branch on what a type can do.

Concepts

A concept names a set of requirements a type must satisfy. Instead of a long list of constraints, you state what operations must exist.

NIM
type
  Printable = concept x
    $x is string

proc show[T: Printable](x: T) = echo "value: ", x

show 42
show "hi"

If a type has no $ operator, the compiler reports that the Printable requirement is not met, in terms the caller can read. Concepts are a newer, still evolving part of Nim: check the manual of your version before relying on advanced forms.

C C stand-in: a function-pointer interface as a poor man's constraint

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

C has no compile-time constraint check, so this runtime table is the closest stand-in. In Nim the check happens at compile time and costs nothing at run time.

Useful standard generics

  • seq[T], array[N, T], openArray[T] for sequences and slices.
  • Option[T] from std/options for "maybe a value".
  • Table[K, V] and HashSet[T] from std/tables and std/sets.

A generic proc can call other generic procs, and overloads work as usual: the most specific match wins.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. When does Nim instantiate a generic proc?

    Each distinct type argument produces its own compiled copy.
  2. 2. What does [T: SomeNumber] do?

    It is a constraint, so non-numeric types are rejected at compile time.
  3. 3. What is a concept?

    Concepts describe which operations a type must support.
  4. 4. What is a downside of monomorphization?

    Every instantiation is separate code, which speeds calls but grows the binary.

Summary

  • Type parameters go in [T] for both procs and types.
  • The compiler generates one specialized copy per type (monomorphization).
  • Constrain with type classes like SomeNumber, or with concepts.
  • Generics are the reuse tool when behavior is the same across types; see Inheritance and Methods when behavior differs.

Next: Templates

ติดตามความคืบหน้าของคุณ

สร้างบัญชีฟรีเพื่อติ๊กบทเรียนที่เรียนแล้วและเรียนต่อจากจุดเดิมได้บนทุกอุปกรณ์