Search code examples
rustownership-semantics

Why does Rust require ownership annotations instead of inferring it?


How come Rust does not fully infer ownership of its variables? Why are annotations needed?


Solution

  • If that were even possible I believe it would be a terrible user experience because:

    • if the compiler cannot deduce ownership of an object, the error can barely be understood (like with trial-and-error approach in C++ templates link);
    • the ownership policy doesn't seem to be easy to grasp (that's one opinion though) and trying to understand which semantic has been chosen by a compiler may lead to unexpected behaviors (reference a Javascript weird type conversions);
    • more bugs during refactoring can be introduced (implied by the point above);
    • full program inference would definitely take a huge amount of time, if it is even a solvable problem.

    However, if you struggle with a lack of polymorphism, it is usually possible to parametrize a method with an ownership kind, which might be considered a somewhat explicit alternative to inference, e.g.:

    fn print_str(s: impl AsRef<str>) {
        println!("{}", s.as_ref());
    }
    
    fn main() {
        print_str("borrowed");
        print_str("owned".to_owned());
    }