Uh oh!
There was an error while loading. Please reload this page.
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);
}
```rust-highfive
commented
Nov 22, 2014
tbu-
commented
Nov 22, 2014
This pull request would change the semantics of Feedback would be appreciated! :) |
alexcrichton
commented
Nov 23, 2014
The I would recommend a description in lines with our breaking changes policy or perhaps a mini-RFC-style description. |
tbu-
commented
Nov 25, 2014
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 |
tbu-
commented
Nov 25, 2014
@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. |
alexcrichton
commented
Nov 25, 2014
I don't think that this is safe, I checked this out and this code compiles (when it shouldn't) fnmain(){let rc = RefCell::new(1u);let b:&uint = {let a = rc.borrow();*a };letmut c = rc.borrow_mut();**c = 3;println!("{}",*b);} |
tbu-
commented
Nov 25, 2014
You're right, this is wrong. I'll look into this. |
SimonSapin
commented
May 25, 2015
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
RefCellcontent, like this code: