(Im)practical Rust:
Never Type
Rust's strong type system allows for some uncommon functionality.
Representing the impossible
Code paths which cannot occur

fn main() -> Result<(), Error> {
    loop {
        // listen to network I/O for example
        // only exits loop if there is an error
    }

    // Is unit the correct representation?
    Ok(())
}
    
Unit Type: ()

For example, functions without a return type implicitly return unit.
Never Type: !

  • Only exists at compile time
  • Not representable in executable code
  • Represents impossibility
  • Common execution impossibilities

  • return
  • continue
  • break
  • These keywords all exit execution to an outer scope, meaning code in the same scope following them can never execute, therefor they implicitly return never.
    Representing the impossible (actually)
    
    fn main() -> Result<!, Error> {
        loop {
            // listen to network I/O for example
            // only exits loop if there is an error
        }
    }
        
    This is a nightly-only experimental API.
    
    #![feature(never_type)]
    let x: ! = {
        return 123
    };
    
    Already representable in today's Rust (sort of).
    std::convert::Infallible

    
    pub enum Infallible {}
        
    
    use std::convert::Infallible as Never;