borrow-checker

How can I convince the borrow checker to allow me to cache values?

落爺英雄遲暮 提交于 2020-01-11 10:21:47
问题 The borrow checker beat me: use std::collections::HashMap; struct Cache { cache: Vec<HashMap<String, String>>, } impl Cache { fn get(&mut self, index: usize, key: String) -> String { let mut cache = &mut self.cache[index]; match cache.get(&key) { Some(r) => { return r.clone(); } None => { let r = "foo".to_string(); // something smart here cache.insert(key, r.clone()); return r; } } } } What I get: error[E0502]: cannot borrow `*cache` as mutable because it is also borrowed as immutable --> src

Pass a Struct<'a>::method as a `for<'a> Fn(&Foo<'a>)` for use in a closure

怎甘沉沦 提交于 2020-01-06 06:53:07
问题 In my tests I had a helper function that runs a given method on differently configured objects, with a simplified version looking like this: fn run_method<F>(f: F) where F: Fn(&Foo), { let to_test = vec![0i32]; to_test .iter() .map(|param| { let foo = Foo(*param); f(&foo); }) .for_each(drop); } // run_method(Foo::run); This worked fine until I added references to the tested struct, making it "lifetime-annotated" (for lack of a proper term, I mean Foo<'a> ). Now I get an error indicating, I

Why can't I store a value and a reference to that value in the same struct?

℡╲_俬逩灬. 提交于 2020-01-06 05:07:26
问题 I have a value and I want to store that value and a reference to something inside that value in my own type: struct Thing { count: u32, } struct Combined<'a>(Thing, &'a u32); fn make_combined<'a>() -> Combined<'a> { let thing = Thing { count: 42 }; Combined(thing, &thing.count) } Sometimes, I have a value and I want to store that value and a reference to that value in the same structure: struct Combined<'a>(Thing, &'a Thing); fn make_combined<'a>() -> Combined<'a> { let thing = Thing::new();

Why can't I store a value and a reference to that value in the same struct?

梦想与她 提交于 2020-01-06 05:07:05
问题 I have a value and I want to store that value and a reference to something inside that value in my own type: struct Thing { count: u32, } struct Combined<'a>(Thing, &'a u32); fn make_combined<'a>() -> Combined<'a> { let thing = Thing { count: 42 }; Combined(thing, &thing.count) } Sometimes, I have a value and I want to store that value and a reference to that value in the same structure: struct Combined<'a>(Thing, &'a Thing); fn make_combined<'a>() -> Combined<'a> { let thing = Thing::new();

Textfile-parsing function fails to compile owing to lifetime/borrow error

安稳与你 提交于 2020-01-05 02:54:07
问题 NB. This post was originally part of a larger post that contained two questions (that I'd believed were one error manifesting itself differently), but to comply with site guidelines I've split it into two separate posts, of which this is the second. The first post is here. I'm trying to parse a simple config text file, which contains one three-word entry per line, laid out as follows: ITEM name value ITEM name value //etc. I've reproduced the function which does the parsing (and the

Will the non-lexical lifetime borrow checker release locks prematurely?

痞子三分冷 提交于 2020-01-04 06:21:08
问题 I've read What are non-lexical lifetimes?. With the non-lexical borrow checker, the following code compiles: fn main() { let mut scores = vec![1, 2, 3]; let score = &scores[0]; // borrows `scores`, but never used // its lifetime can end here scores.push(4); // borrows `scores` mutably, and succeeds } It seems reasonable in the case above, but when it comes to a mutex lock, we don't want it to be released prematurely. In the following code, I would like to lock a shared structure first and

How is a destructor call `fn drop(&mut self)` call inserted when the owning variable is immutable?

社会主义新天地 提交于 2020-01-03 11:37:20
问题 It is my understanding that when a variable whose type implements Drop goes out of scope, a call to the fn drop(&mut self) function is inserted, and passed a newly-created mutable reference to the variable going out of scope. However, how is that possible in cases where the variable was immutably bound, and it would be illegal to borrow it mutably? Here's an example of what I'm talking about: fn main() { let x = vec![1, 2, 3]; let y = &mut x; } Which produces the following error: cannot

Borrowed value does not live long enough when creating a Vec

那年仲夏 提交于 2020-01-01 12:15:24
问题 Editor's note: This question was asked before Rust 1.0. Since then, many functions and types have changed, as have certain language semantics. The code in the question is no longer valid, but the ideas expressed in the answers may be. I'm trying to list the files in a directory and copy the filename to my own Vec . I've tried several solutions, but it always ends up with a problem of not being able to create long enough living variables. I don't understand my mistake. fn getList(action_dir

Rust matching and borrow checker

蓝咒 提交于 2019-12-31 06:37:15
问题 I keep stumbling on a pattern in my Rust programs that always puts me at odds with the borrow-checker. Consider the following toy example: use std::sync::{Arc,RwLock}; pub struct Test { thing: i32, } pub struct Test2 { pub test: Arc<RwLock<Test>>, pub those: i32, } impl Test { pub fn foo(&self) -> Option<i32> { Some(3) } } impl Test2 { pub fn bar(&mut self) { let mut test_writer = self.test.write().unwrap(); match test_writer.foo() { Some(thing) => { self.add(thing); }, None => {} } } pub fn

Rust matching and borrow checker

≯℡__Kan透↙ 提交于 2019-12-31 06:36:49
问题 I keep stumbling on a pattern in my Rust programs that always puts me at odds with the borrow-checker. Consider the following toy example: use std::sync::{Arc,RwLock}; pub struct Test { thing: i32, } pub struct Test2 { pub test: Arc<RwLock<Test>>, pub those: i32, } impl Test { pub fn foo(&self) -> Option<i32> { Some(3) } } impl Test2 { pub fn bar(&mut self) { let mut test_writer = self.test.write().unwrap(); match test_writer.foo() { Some(thing) => { self.add(thing); }, None => {} } } pub fn