borrow-checker

How can I simultaneously iterate over a Rust HashMap and modify some of its values?

穿精又带淫゛_ 提交于 2019-12-01 21:06:07
问题 I'm trying Advent of Code in Rust this year, as a way of learning the language. I've parsed the input (from day 7) into the following structure: struct Process { name: String, weight: u32, children: Vec<String>, parent: Option<String> } These are stored in a HashMap<String, Process> . Now I want to iterate over the values in the map and update the parent values, based on what I find in the parent's "children" vector. What doesn't work is for p in self.processes.values() { for child_name in p

Changing a node in a tree in Rust

北战南征 提交于 2019-12-01 20:02:27
I'm trying to write a function that, given a tree structure, returns a copy of that tree but with a node changed at a particular index. Here is what I have so far: #[derive(Clone)] pub enum Node { Value(u32), Branch(u32, Box<Node>, Box<Node>), } fn main() { let root = Node::Branch(1, Box::new(Node::Value(2)), Box::new(Node::Value(3))); zero_node(&root, 2); } pub fn zero_node (tree: &Node, node_index: u8) -> Node { let mut new_tree = tree.clone(); fn zero_rec (node : &mut Node, node_count : u8, node_index : u8) -> u8 { if (node_index == node_count) { match node { &mut Node::Value(_) => { *node

Why is indexing a mutable vector based on its len() considered simultaneous borrowing?

[亡魂溺海] 提交于 2019-12-01 18:58:33
I know the general answer — You can only borrow mutably once or immutably many times, but not both. I want to know why this specific case is considered simultaneous borrowing. I have the following code: fn main() { let mut v = vec![1, 2, 3, 4, 5]; let n = 3; // checks on n and v.len() and whatever else... let mut s = v[..n].to_vec(); for i in 0..n { v[i + v.len() - n] = s[1]; } } which produces the following error under 1.36.0: error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable --> src/main.rs:7:15 | 7 | v[i + v.len() - n] = s[1]; | ------^----------- | | | | |

Want to add to HashMap using pattern match, get borrow mutable more than once at a time

爷,独闯天下 提交于 2019-12-01 15:03:57
I am trying to write some toy code that stores the number of times it sees a word in a HashMap . If the key exists, it increments a counter by one, if the key doesn't exist, it adds it with the value 1 . I instinctively want to do this with a pattern match, but I hit a borrow mutable more than once error: fn read_file(name: &str) -> io::Result<HashMap<String, i32>> { let b = BufReader::new(File::open(name)?); let mut c = HashMap::new(); for line in b.lines() { let line = line?; for word in line.split(" ") { match c.get_mut(word) { Some(i) => { *i += 1; }, None => { c.insert(word.to_string(), 1

Want to add to HashMap using pattern match, get borrow mutable more than once at a time

社会主义新天地 提交于 2019-12-01 14:39:04
问题 I am trying to write some toy code that stores the number of times it sees a word in a HashMap . If the key exists, it increments a counter by one, if the key doesn't exist, it adds it with the value 1 . I instinctively want to do this with a pattern match, but I hit a borrow mutable more than once error: fn read_file(name: &str) -> io::Result<HashMap<String, i32>> { let b = BufReader::new(File::open(name)?); let mut c = HashMap::new(); for line in b.lines() { let line = line?; for word in

Why does the parameter “borrow” the value? [duplicate]

自作多情 提交于 2019-12-01 11:10:08
问题 This question already has an answer here : Borrow checker and function arguments in Rust, correct or over zealous? [duplicate] (1 answer) Closed last year . Here is a sample: struct X(u32); impl X { fn f(&mut self, v: u32) {} } fn main() { let mut x = X(42); // works let v = x.0; x.f(v); // cannot use `x.0` because it was mutably borrowed x.f(x.0); } (Rust playground) error[E0503]: cannot use `x.0` because it was mutably borrowed --> src/main.rs:16:9 | 16 | x.f(x.0); | - ^^^ use of borrowed

Can't borrow mutably within two different closures in the same scope

↘锁芯ラ 提交于 2019-12-01 09:15:32
My goal is to make a function (specifically, floodfill) that works independent of the underlying data structure. I tried to do this by passing in two closures: one for querying, that borrows some data immutably, and another for mutating, that borrows the same data mutably. Example (tested on the Rust Playground ): #![feature(nll)] fn foo<F, G>(n: i32, closure: &F, mut_closure: &mut G) where F: Fn(i32) -> bool, G: FnMut(i32) -> (), { if closure(n) { mut_closure(n); } } fn main() { let mut data = 0; let closure = |n| data == n; let mut mut_closure = |n| { data += n; }; foo(0, &closure, &mut mut

Getting “temporary value dropped while borrowed” when trying to update an Option<&str> in a loop

冷暖自知 提交于 2019-12-01 08:50:07
问题 I'm trying to implement a commonly used pattern - using the result of a previous loop iteration in the next loop iteration. For example, to implement pagination where you need to give the id of the last value on the previous page. struct Result { str: String, } fn main() { let times = 10; let mut last: Option<&str> = None; for i in 0..times { let current = do_something(last); last = match current { Some(r) => Some(&r.str.to_owned()), None => None, }; } } fn do_something(o: Option<&str>) ->

Borrow checker on parent-child relation

十年热恋 提交于 2019-12-01 08:41:10
I have the code below producing the error message marked in its comments. I think I understand the message: I want to borrow parent two times: once for finding its child, and once as an argument to the child (and the mutable/immutable words in the error are not relevant). I have to prove that Child doesn't disappear when it modifies Parent . But I don't know how to do this. I could Rc<Child> everything but that seams wasteful, so I hope adding some lifetimes would do the trick. struct Parent { used: i32, child: Child, } struct Child { dummy: i32, } impl Child { fn use_parent(&mut self, parent:

Best way to remove elements of Vec depending on other elements of the same Vec

谁说我不能喝 提交于 2019-12-01 08:14:20
I have a vector of sets and I want to remove all sets that are subsets of other sets in the vector. Example: a = {0, 3, 5} b = {0, 5} c = {0, 2, 3} In this case I would like to remove b , because it's a subset of a . I'm fine with using a "dumb" n² algorithm. Sadly, it's pretty tricky to get it working with the borrow checker. The best I've come up with is ( Playground ): let mut v: Vec<HashSet<u8>> = vec![]; let mut to_delete = Vec::new(); for (i, set_a) in v.iter().enumerate().rev() { for set_b in &v[..i] { if set_a.is_subset(&set_b) { to_delete.push(i); break; } } } for i in to_delete { v