Void is surprisingly useful.
Void is surprisingly useful.
Posted Sep 9, 2026 16:40 UTC (Wed) by NYKevin (subscriber, #129325)In reply to: Void is surprisingly useful. by alx.manpages
Parent article: Stabilizing Rust's never type
* A user-supplied callback function might be void, so we need not propagate its return value.
* The user might only want to use part of our container (e.g. using a hash table as a hash set), so we need not store the rest.
* A user-supplied function might be infallible, so we need not handle errors.
In other words, the vast majority of cases just look like deleting some code that we don't need. So you don't really need optional type parameters, you just need types that tell the compiler to delete some code. That gives us () and !:
* () ("unit") means roughly "don't emit code to store or pass along values of this type." It's a type whose only value is always constant-folded out of existence. It's good for cases where we want the code to do basically the same thing, except without storing a value.
* ! ("never") means roughly "don't emit code in any scope where a value of this type is observed to exist." It's a type with no values, so you don't need any code to handle it. It's good for cases where we want some branch(es) to disappear entirely, e.g. for removing error handling or otherwise forcing compile-time evaluation of something.
! has the additional behavior of making some pattern matches infallible. If we have a Result<V, !>, it may be infallibly pattern-matched against Ok(v) because Rust knows the Err() case can't exist. This doesn't work with Result<V, ()>, because that means "there is an error case, but no error information is provided" (similar to Option<V>).
