4 ms·
> When handing out references of something bound with let mut, why do i need to do &mut instead of just & ? Sometimes, you still want to immutably borrow a mut
by saghm 9y ago
> When handing out references of something bound with let mut, why do i need to do &mut instead of just & ?
Sometimes, you still want to immutably borrow a mutable variable. Otherwise, you wouldn't be able to have multiple references to a variable declared with `mut`, which would be an unnecessary limitation.
EDIT: Here's an example of something that wouldn't otherwise work if borrows of mutable variables were implicitly mutable:
struct Point {
x: i32,
y: i32,
}
fn add(p1: &Point, p2: &Point) -> Point {
let x = p1.x + p2.x;
let y = p1.y + p2.y;
Point { x: x, y: y }
}
fn main() {
let mut some_point = Point { x: 1, y: 1 };
some_point.x = 2;
// `some_point` is borrowed twice here, which wouldn't be possible if the borrows were mutable.
let other_point = add(&some_point, &some_point);
println!("({}, {})", other_point.x, other_point.y);
}
- skywhopper 9y agoMy best interpretation of his question was more along the lines of: why do you have to mark it as `mut` if you aren't going to change it in the function? Suddenly your function only accepts mutable pointers, not just any pointer.
- eridius 9y agoWell, you wouldn't. The example function in the blog post isn't mutating the argument, but that's why the comment says // This uses mut for no reason other than to prove a point. You wouldn't normally have a function accept a mutable reference if it's not mutating it.
- jackmott 9y agoit would be a compiler warning if you did, too.
- kibwen 9y agoRust deliberately doesn't do interprocedural analysis, so function signatures are the ultimate source of truth. If you want to call a function that takes a `&mut` then all the rules for taking a `&mut` apply. If the function that takes a `&mut` doesn't need a `&mut`, however, then that's probably just bad API design, and is something to be avoided (I've never seen any such thing in the wild; the guideline in API design is to make your function signatures as unrestrictive as you can, and `&mut` is as restrictive as it gets).
- kevincox 9y agoTo me it lets me know if an object will be changed by the function or not. If it's just & I know that my object is just how I left it. If it is &mut I need to think about how it was changed.
- scottlamb 9y agoTo 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.
- kllrnohj 9y agoThe question isn't why does the function decleration need to have &mut, it's why does the call site need to have &mut? as in assume you had: fn reset(p: &mut Point) { p.x = 0; p.y = 0; } Why can't this be called like so: reset(&some_point); rather than needing to say reset(&mut some_point); To some extent it's nice that the callsite must document the behavior visually, but its more forcing a style guide rather than anything that's required to compile & work.
- phaylon 9y agoYou can implement traits for both kinds of references, so a function might accept both.
- johncolanduoni 9y agoThe same thing can still happen with Deref coercions or type inference, so this is something the compiler already has to deal with.
- phaylon 9y agoI'm not sure what you mean. Can you give an example?
- johncolanduoni 9y agoIf struct A implements trait S and trait T, and there are two functions fn foo(x: &S); fn foo(y: &T); in scope, then the compiler needs you to disambiguate foo(&a) if a: A. This isn't a whole lot different than disambiguating the same expression if the functions are: fn foo(x: &A); fn foo(x: &mut A);
- saghm 9y agoWhen you use `&mut some_point`, (i.e. immutably borrow "some_point"), the compiler requires that "some_point" is not borrowed anywhere else at the same time. In order to enforce that invariant, it needs to know what borrows are mutable and what borrows are immutable. Perhaps what you're wondering is "why can't the compiler infer when a borrow needs to be mutable instead of having the programmer specify it"? I can't say for certain what the answer to this is, but my guess is that it would be rather expensive. Consider this example (reusing the "add" function from above): let mut foo = Point { x: 1, y: 2 }; let bar = &foo; add(&foo, &foo); ... // Much later reset(bar); Under the proposed "mutable reference inference" rules, should this compile? It's not necessarily trivial to determine this (especially if the "..." contains a lot of code), but it should not, since `bar` must a be mutable borrow to be able to pass into `reset`, which means that the borrows of `foo` to pass to `add` shouldn't be allowed. This means that the compiler would have to a rather expensive lookahead to determine whether any borrows are valid (and some people already complain that Rust compiles too slowly!). Forcing users to specify when borrows are mutable makes the compilers job much easier, not to mention the readability benefits that comes from making mutability explicit.