16 ms·
To the compiler, too. if it's just &, the compiler knows the pointee is just how it left it[1], and it can optimize on this assumption. For example, if it had
by scottlamb 9y ago
To the compiler, too.
if it's just &, the compiler knows the pointee is just how it left it[1], and it can optimize on this assumption. For example, if it had the contents in a register before the call, it knows they're still valid after the call. This is the same sort of thing "restrict" gives you in C, but unlike "restrict", using & is idiomatic and the compiler will spot mistakes.
If it's &mut, those assumptions aren't valid.
[1] except, iiuc, the contents of UnsafeCells (and things built on top of them, such as RefCell).
- kevincox 9y agoWell the compiler knows the signature of the function you pass it to so it should be able to optimize it anyways. I think in most if not all cases the compiler can figure out if &thing needs a mutable or immutable reference. I think the only difference is the readability to the programmer and I agree with the decision made requiring &mut for a mutable reference.
- steveklabnik 9y ago> so it should be able to compile it anyways. &T vs &mut T is very significant in Rust; not only the stuff that the parent brought up, but also variance. It's not a simple lint.
- kevincox 9y agoSorry, I typed the wrong word. I've updated the parent to be less confusing. s/compile/optimize/ For reference the first line used to be: "Well the compiler knows the signature of the function you pass it to so it should be able to compile it anyways." > &T vs &mut T is very significant in Rust Yes, especially for function signatures it is critical, however the ancestor was talking about using & to take a reference. When using & to take a reference I don't think &mut needs to be required. The compiler could probably figure it out.
- scottlamb 9y agoOh, I'm talking about having the type of reference declared in the function signature. Yes, I agree repeating it in the invocation is for the programmer's benefit. Rust doesn't have overloading, so there's no ambiguity.