borrow-checker

Moving value out of function by dereferencing a reference [duplicate]

家住魔仙堡 提交于 2020-01-25 06:52:11
问题 This question already has answers here : Why is it legal to borrow a temporary? (3 answers) Why can I return a reference to a local literal but not a variable? (1 answer) Cannot move out of borrowed content / cannot move out of behind a shared reference (1 answer) Closed last month . Given this code: struct SimpleFoo {} fn create_simplefoo() -> SimpleFoo { let foo: &SimpleFoo = &SimpleFoo {}; *foo } pub fn main() { let foo = create_simplefoo(); } I get error[E0507]: cannot move out of `*foo`

Cannot assign to `self.x` because it is borrowed

喜夏-厌秋 提交于 2020-01-24 23:58:07
问题 I have 2 functions: // A simple struct struct S { w: u8, h: u8, x: Vec<u8>, y: Vec<u8>, } // Implementation of the struct S impl S { // Seems to work fn new(_w: u8, _h: u8, _x: &Vec<u8>, _y: &Vec<u8>) -> S { S { w: _w, h: _h, x: _x.clone(), y: _y.clone(), } } fn calc(&mut self) { let mut min_x = self.x.iter().min().unwrap(); let mut max_x = self.x.iter().max().unwrap(); let mut min_y = self.y.iter().min().unwrap(); let mut max_y = self.y.iter().max().unwrap(); // Here's the line that gives

Textfile-parsing function fails to compile owing to type-mismatch error

我只是一个虾纸丫 提交于 2020-01-24 19:10:27
问题 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 subsequent compilation error) here (and on the Rust Playpen): pub fn parse(path: &Path) -> config_struct { let file = File::open(&path).unwrap(); let reader = BufReader::new(&file); let line_iterator = reader.lines(); let mut connection_map = HashMap::new(); let mut target_map =

Why does Vec<T>::split_at_mut borrow the vector for the rest of the scope?

断了今生、忘了曾经 提交于 2020-01-24 17:32:06
问题 Vec<T> has two methods: fn push(&mut self, value: T) fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) They both take a mutable reference to the vector. But the scope of the borrow seems to be different, e.g: fn works() { let mut nums: Vec<i64> = vec![1,2,3,4]; nums.push(5); println!("{}", nums.len()); } fn doesnt_work() { let mut nums: Vec<i64> = vec![1,2,3,4]; let (l,r) = nums.split_at_mut(2); println!("{}", nums.len()); } fn also_works() { let mut nums: Vec<i64> = vec![1,2,3,4

Cannot borrow `*self` as mutable more than once at a time when returning a Result containing a reference

落花浮王杯 提交于 2020-01-22 03:32:28
问题 Why is the following invalid and what should I do instead to make it work? struct Foo; impl Foo { fn mutable1(&mut self) -> Result<(), &str> { Ok(()) } fn mutable2(&mut self) -> Result<(), &str> { self.mutable1()?; self.mutable1()?; Ok(()) } } This code yields: error[E0499]: cannot borrow `*self` as mutable more than once at a time --> src/lib.rs:10:9 | 8 | fn mutable2(&mut self) -> Result<(), &str> { | - let's call the lifetime of this reference `'1` 9 | self.mutable1()?; | ---- - returning

How do I write a rust function that can both read and write to a cache?

时光毁灭记忆、已成空白 提交于 2020-01-16 14:39:48
问题 Original Problem Statement I'm trying to write a function that can both read and write from a cache, but I'm running into a problem where the compiler says I can't both mutably and immutably borrow the cache. I've read through https://doc.rust-lang.org/book/ch04-02-references-and-borrowing.html , https://naftuli.wtf/2019/03/20/rust-the-hard-parts/ and random stack overflow/Reddit posts, but I can't see how to apply what they say to this code. use std::collections::HashMap; struct

Rust Borrow checker only complains about borrowing as mutable multiple times when a function that returns a reference with the same lifetime assigned

做~自己de王妃 提交于 2020-01-15 09:20:10
问题 I'm having problem with some Rust code where I'm being allowed to borrow something as mutable more than once on certain conditions (first confusing part), but not others. I've written the following example to illustrate: (Playground) struct NoLifetime {} struct WithLifetime <'a> { pub field: &'a i32 } fn main() { let mut some_val = NoLifetime {}; borrow_mut_function(&mut some_val); borrow_mut_function(&mut some_val); // Borrowing as mutable for the second time. let num = 5; let mut life_val =

Drop a immutable borrow to make a mutable borrow

痴心易碎 提交于 2020-01-14 19:29:05
问题 I am still learning Rust and when trying to implement Dikjstra as part of a training project, I encountered this peculiar catch. First I define a HashMap : let mut dist: HashMap<Node, usize> = HashMap::new(); And later: let state = State { node: next_node.clone(), cost: cost + 1 }; let current_dist = dist.get(&state.node); if (current_dist == None) || (state.cost < *current_dist.unwrap()) { dist.insert(state.node.clone(), state.cost); heap.push(state); } Which yields a compile error because

cannot borrow variable as mutable because it is also borrowed as immutable while building a self-referential HashMap

时光总嘲笑我的痴心妄想 提交于 2020-01-11 13:21:13
问题 I'm trying to build a self-referential HashMap : use std::collections::HashMap; struct Node<'a> { byte: u8, map: HashMap<i32, &'a Node<'a>>, } fn main() { let mut network = HashMap::<u32, Node>::new(); network.insert(0, Node { byte: 0, map: HashMap::<i32, &Node>::new() }); network.insert(1, Node { byte: 1, map: HashMap::<i32, &Node>::new() }); let zeroeth_node = network.get(&0).unwrap(); let mut first_node = network.get_mut(&1).unwrap(); first_node.map.insert(-1, zeroeth_node); } I'm running

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

北战南征 提交于 2020-01-11 10:21:48
问题 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