How come Rust does not fully infer ownership of its variables? Why are annotations needed?
Asked
Active
Viewed 102 times
-1
-
1What are "ownership annotations"? Do you mean like how `self` and `&self` are different ways to write a method? Or do you mean lifetime annotations? – trent Jun 27 '20 at 13:15
-
@trentcl Good link, thanks! I guess the rationale is similar, that full inference is in principle possible but maybe not desirable for usage purpose. – Olle Härstedt Jun 27 '20 at 13:53
1 Answers
2
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());
}

Kitsu
- 3,166
- 14
- 28
-
Hm, well full inference does not contradict optional annotations. But it really has to work fully without any annotations. – Olle Härstedt Jun 27 '20 at 13:21
-
1More open question here (but unanswered): https://cstheory.stackexchange.com/questions/47126/is-full-ownership-inference-possible – Olle Härstedt Jul 13 '20 at 21:46