-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add map
function to Ref
and MutRef
of RefCell
#19220
Conversation
This enables one to return references to things inside the primary `RefCell` content, like this code: ``` use std::cell::RefCell; use std::cell::Ref; struct ContainsVector { vec: RefCell<Vec<u32>>, } impl ContainsVector { fn new() -> ContainsVector { ContainsVector { vec: RefCell::new(vec![0]) } } fn index<'a>(&'a self, i: uint) -> Ref<'a, &'a u32> { self.vec.borrow().map(|v| &v[i]) } fn index_mut<'a>(&'a self, i: uint) -> RefMut<'a, &'a mut u32> { self.vec.borrow_mut().map(|v| &mut v[i]) } } fn main() { let cv = ContainsVector::new(); **cv.index_mut(0) = 1; cv.index(0); } ```
This pull request would change the semantics of Feedback would be appreciated! :) |
The I would recommend a description in lines with our breaking changes policy or perhaps a mini-RFC-style description. |
MotivationPreviously, you were unable to return a reference to something non-trivial inside of a
Then you're currently unable to return a reference an element of the vector, despite this having somewhat clear semantics (it would keep the Proposed changesThis proposal changes the direct usage semantics of the AdvantagesThis should be the most simple change in order to properly return references to inner members of Before (approximation):
After:
(So the assembly output still just contains one dereference.) DisadvantagesUsage sites that do not benefit from auto-derefencing need to be changed. This includes e. g.
to
|
@alexcrichton I believe the biggest argument against this change is that it changes a core type – however since we're still pre-1.0 it might be a bigger concern to get it right than to maintain backward-compatiblity. |
I don't think that this is safe, I checked this out and this code compiles (when it shouldn't) fn main() {
let rc = RefCell::new(1u);
let b: &uint = {
let a = rc.borrow();
*a
};
let mut c = rc.borrow_mut();
**c = 3;
println!("{}", *b);
} |
You're right, this is wrong. I'll look into this. |
I’m making another attempt at this in #25747. |
…up-doc doc: remove nit from setup.md
This enables one to return references to things inside the primary
RefCell
content, like this code: