Found this trick to make working with generics better

Normally, for a proc like this one:

t_proc :: proc(data: $T) {
	if data < nil {}
}
main :: proc() {}

You can tell there is a compile error here but this program builds just fine.

I’m guessing because the compiler can’t check for every possible type this can be, it instead checks based on actual usage. Since this proc isn’t used anywhere, it doesn’t get checked.

My earlier workarounds were kinda hacky, like:

making a temporary alias, and when I’m done, change it to $T:

T :: uint
t_proc :: proc(data: T) {
	if data < nil {}
}
main :: proc() {}

or, actually using the proc:

t_proc :: proc(data: $T) {
	if data < nil {}
}
main :: proc() { t_proc(uint(0)); }

but both methods are kinda annoying to do for every proc.

Today, I realized I could do this:

t_proc :: proc(data: $T = uint(0)) {
	if data < nil {}
}
main :: proc() {}

This program doesn’t build.

Honestly, seems really obvious in retrospect, so maybe I’m the only one who didn’t know, but I thought I’d share it just in case.

This even enables OLS to catch errors on save, pretty sweet.

4 Likes