Special types
Unit
A tuple with zero elements is called unit type, which acts as a no-type similar to void
in C++.
Without returning a value, a function will return an unit type. On the other side, a function with no return signature will default to the unit type, as well.
// All valid and equivalent
fn one_function() {}
fn other_function() -> () {
let unused: usize = 0;
}
fn another_function() {
return ();
}
Never
At the date of writing, this type can only be used explicitly in the nightly version of Rust. It denotes the return type of a function that will just never return. The prime example of this is the panic!
macro. In a code block that panics, it doesn't make sense to make up some garbage data, only to satisfy the function signature. Thus, returning a value after encountering a never
value is optional and doesn't have any effect.
fn can_panic(will_panic: bool) -> bool {
if will_panic {
// Returning after here wouldn't be reachable and thus doesn't make sense
panic!();
} else {
return false;
}
}