3 ms·
You cannot return an immutable version. You can return it owned (in which case you can assign/reassign it to a mut variable at any point) or you can take a mut
by vlovich123 11mo ago
You cannot return an immutable version. You can return it owned (in which case you can assign/reassign it to a mut variable at any point) or you can take a mut reference and return an immutable reference - but whoever is the owner can almost always access it mutably.
- pkulak 11mo agoArg, you’re right. Not sure what I was thinking there. I still think my point stands, because you get the benefits of immutability, but yeah, I didn’t explain it well.
- tekne 11mo agoI mean, if you return an immutable reference, the owner in fact cannot mutate it until that reference is dropped. If you in fact return e.g. an Rc::new(thing) or Arc::new(thing), that's forever (though of course you can unwrap the last reference!)
- aw1621107 11mo ago> I mean, if you return an immutable reference, the owner in fact cannot mutate it until that reference is dropped. Might be worth noting that "dropped" in this context doesn't necessarily correspond to the reference going out of scope: fn get_first(v: &Vec<i32>) -> &i32 { &v[0] } fn main() { let mut v = vec![0, 1, 2]; let first = get_first(&v); print!("{}", first}); v.push(3); // Works! // print!("{}", first); // Doesn't work }