borrow-checker

Mutable borrow in a getter not living long enough

左心房为你撑大大i 提交于 2019-12-29 09:06:27
问题 pub type Data = i32; pub struct Foo { data: Data, } impl Foo { pub fn data_mut(&mut self) -> &mut Data { &mut self.data } } pub struct Context { data: Data, foos: Vec<Foo>, } impl Context { pub fn broken(&mut self) -> &mut Data { // What are the lifetimes here that make this version not work? &mut self.foos.first_mut().unwrap().data_mut() } pub fn working(&mut self) -> &mut Data { &mut self.foos.first_mut().unwrap().data } } fn main() {} (Playground) error[E0597]: borrowed value does not live

Mutable borrow in a getter not living long enough

ⅰ亾dé卋堺 提交于 2019-12-29 09:05:43
问题 pub type Data = i32; pub struct Foo { data: Data, } impl Foo { pub fn data_mut(&mut self) -> &mut Data { &mut self.data } } pub struct Context { data: Data, foos: Vec<Foo>, } impl Context { pub fn broken(&mut self) -> &mut Data { // What are the lifetimes here that make this version not work? &mut self.foos.first_mut().unwrap().data_mut() } pub fn working(&mut self) -> &mut Data { &mut self.foos.first_mut().unwrap().data } } fn main() {} (Playground) error[E0597]: borrowed value does not live

Borrow checker doesn't realize that `clear` drops reference to local variable

无人久伴 提交于 2019-12-29 08:27:26
问题 The following code reads space-delimited records from stdin, and writes comma-delimited records to stdout. Even with optimized builds it's rather slow (about twice as slow as using, say, awk). use std::io::BufRead; fn main() { let stdin = std::io::stdin(); for line in stdin.lock().lines().map(|x| x.unwrap()) { let fields: Vec<_> = line.split(' ').collect(); println!("{}", fields.join(",")); } } One obvious improvement would be to use itertools to join without allocating a vector (the collect

Mutable borrow of self doesn't change to immutable

谁说胖子不能爱 提交于 2019-12-29 06:44:09
问题 This code fails the dreaded borrow checker (playground): struct Data { a: i32, b: i32, c: i32, } impl Data { fn reference_to_a(&mut self) -> &i32 { self.c = 1; &self.a } fn get_b(&self) -> i32 { self.b } } fn main() { let mut dat = Data{ a: 1, b: 2, c: 3 }; let aref = dat.reference_to_a(); println!("{}", dat.get_b()); } Error: error[E0502]: cannot borrow `dat` as immutable because it is also borrowed as mutable --> <anon>:19:20 | 18 | let aref = dat.reference_to_a(); | --- mutable borrow

Option<Receiver> Moved in Previous Loop Iteration

落花浮王杯 提交于 2019-12-25 02:59:11
问题 I'm spawning a thread that does some work. Sometimes I want this thread to die after the work is finished, other times I want it to wait for more work to do. To do this I pass in an Option<Receiver<T>> . If Option<Receiver<T>> is None the thread should die, else it should wait to receive more work. fn foo(rx: Option<Receiver<usize>>) { thread::spawn(move || { loop { do_some_work(); if let Some(r) = rx { match r.recv() { Ok(x) => {} Err(_) => panic!("Oh no!"), } } else { break; //Die } } }); }

How can I pattern match a tuple containing a &mut enum and use the enum in the match arm?

落爺英雄遲暮 提交于 2019-12-24 18:34:49
问题 How can the code below be made to compile? It seems perfectly safe, but can't convince the compiler that it is. The version matching *self gives the error: cannot move out of borrowed content on the line of the match The version matching self gives: use of moved value: *self enum Foo { Foo1(u32), Foo2(i16), } impl Foo { fn bar(&mut self, y: u32) -> (u32, &mut Foo) { match (*self, y) { (Foo::Foo1(ref mut a), b) if (b == 5) => { print!("is five"); *a = b + 42; (b, self) } (Foo::Foo2(ref mut a),

How to end borrow when an Option is None [duplicate]

↘锁芯ラ 提交于 2019-12-24 14:09:56
问题 This question already has answers here : How to update-or-insert on a Vec? (2 answers) How to get an Option's value or set it if it's empty? (1 answer) Why is a borrow still held in the else block of an if let? (5 answers) Returning a reference from a HashMap or Vec causes a borrow to last beyond the scope it's in? (1 answer) How to end a borrow in a match or if let expression? (2 answers) Closed last year . The following code will fail the borrow checker: fn at(&mut self, i: usize) -> Option

match + RefCell = X does not live long enough

最后都变了- 提交于 2019-12-24 01:05:05
问题 I need to initialize an item ( fn init(&mut self) -> Option<&Error> ), and use it if there's no errors. pub fn add(&mut self, mut m: Box<Item>) { if let None = m.init() { self.items.push(m); } } This works unless I need to check the error if there's any: pub fn add(&mut self, mut m: Box<Item>) { if let Some(e) = m.init() { //process error } else { self.items.push(m); //won't compile, m is borrowed } } Fair. Need to use RefCell . However, this pub fn add(&mut self, mut m: Box<Item>) { let rc =

Borrow checker error after adding generic parameter to struct

自作多情 提交于 2019-12-24 00:29:33
问题 I have code that works, but it stops compiling with a borrow checker error after a change. I don't understand how the change could affect borrow checking. Common part to both working and non-working code: /// Some struct that has references inside #[derive(Debug)] struct MyValue<'a> { number: &'a u32, } /// There are many structs similar to `MyValue` and there is a /// trait common to them all that can create them. In this /// example I use the `From` trait. impl<'a> From<&'a u32> for MyValue

Is it possible to borrow parts of a struct as mutable and other parts as immutable?

99封情书 提交于 2019-12-23 22:56:49
问题 Is it possible to borrow parts of a struct as mutable, and another part as immutable - if the struct's fields are private. fn main() { let mut ecs = EntityComponentSystem::new(); for e_id in ecs.get_entities_with_component::<Velocity>().unwrap() { let components = ecs.get_mut_components(e_id); ... } impl EntityComponentSystem { ... pub fn get_entities_with_component<K: Key>(&self) -> Option<&HashSet<u64>> { self.entities_with_components.get(&TypeId::of::<K>()) } pub fn get_mut_components(&mut