The purpose of (not) returning noreturn

I noticed following function in in the struct WasiThreadImpl in Thread.zig:

    fn getCpuCount() error{Unsupported}!noreturn {
        return error.Unsupported;
    }

What’s the thinking behind using noreturn here (instead of usize)? It’s counter-intuitive.

You’re not supposed to call it if you’re targeting WebAssembly. Why would call it if you’re guaranteed to not get the answer you want? Use compile-time dispatching to avoid the call.
My previous answer easnt’t great. Here’s a better answer, that elaborates on what @dimdin mentioned below.
noreturn is like unreachable but for return values, therefore, in this case, it lets the compiler know that return value will always be an error. The compiler can propagate this upward and apply optimizations.

It does not have meaning for this specific getCpuCount implementation but it may have meaning for other implementations.

An better example with noreturn error union:

fn loop() error{Failure}!noreturn {
    while (true) {
        if (!poll())
            return error.Failure;
    }
}
5 Likes

Please note that error{Failure}!noreturn is equivalent to error{Failure}.

4 Likes