TIL: Rust's never type

rust

alt text

An interesting thing I learned today was the Never type.

! represents the type of computations which never resolve to any value at all. For example, the exit function fn exit(code: i32) -> ! exits the process without ever returning, and so returns !. break, continue and return expressions also have type !

Reference: https://doc.rust-lang.org/stable/std/primitive.never.html

this is also why returns have optional semicolons because returns are also considered expressions of a type ! (never)

The ! type is a concept in Rust that helps in representing expressions or functions that never produce a value and enables optimizations around such code paths. It is useful in handling cases like infinite loops, error handling, and simplifying control flow.

Other things to consider about how a ; is optional for returns.

  • No semicolon at the end of an expression: It is an expression that returns a value.
  • Semicolon at the end of an expression: It turns the expression into a statement, and does not return a value.
  • Return keyword: Can be used to explicitly return a value at any point, making the semicolon at the end of the line mandatory.