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:

    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());
    }