How does the compiler know two generic types are the same?

Misconception alert! :wink:

In modern Zig, function memoization is purely an optimization: it does not impact language semantics and will not be a part of the language specification.

Instead, the compiler determines whether types are equivalent by comparing two things:

  • Where are the types declared in source code?
  • What values do the type definitions “capture” – meaning, what is the value of any identifier used within the type’s definition but declared outside of it?

Here’s a simple example:

fn Foo(comptime val: anytype) type {
    const T = @TypeOf(val);
    return struct { x: T };
}

The struct declaration in this function captures the value of the local variable T, so whether two types Foo(x) and Foo(y) are equivalent depends on what T is in each case. For instance, Foo("hello") == Foo("world"), and Foo(1) == Foo(2), but Foo(1) != Foo(1.0).

10 Likes