logoalt Hacker News

Xirdus • today at 8:04 PM • 3 replies • view on HN

Mathematically, types are sets of possible values.

Any type (like in TypeScript; Rust doesn't have one) is a set of every possible value; a supertype of all types. Every expression regardless of type can be assigned to a variable of type any.

The opposite is the never type, which is an empty set; no value is of type never. Per set theory, an empty set is a subset of every set, which makes the never type a subtype of all types. An expression of type never can be assigned to every variable regardless of type.

If never type has no values, then how can an expression have never type? Easy: it must never evaluate. Infinite loops, unconditional panics/exceptions, process exit/abort, etc. Also, generics - you can have Vec<!> that's always empty, Result<T,!> that can never be an error, etc.


Replies

rcxdude • today at 9:15 PM

Rust does have https://doc.rust-lang.org/std/any/trait.Any.html but it's not quite the same thing (for one thing, it's not actually all types).

➕ show 1 reply
afdbcreid • today at 9:19 PM

Also called top and bottom types, for this reason.

➕ show 1 reply
boston_clone • today at 8:29 PM

Comprehensive yet succinct, and appreciate you tying it to math - that helped solidify the idea.