borrow-checker

How can a nested loop with mutations on a HashMap be achieved in Rust?

半腔热情 提交于 2019-12-10 17:32:06
问题 I have the following (trimmed down) Rust code: use std::collections::HashMap; struct Node { weight: f64, outbound: f64, } struct Graph { edges: HashMap<u32, HashMap<u32, f64>>, nodes: HashMap<u32, Node>, } impl Graph { fn mutate(&mut self) { for (key, value) in self.nodes.iter() { if self.edges.contains_key(key) { for (target, weight) in self.edges[key].iter() { self.nodes.entry(*target).or_insert(Node::new()).weight; } } } } } However, I cannot get the code to compile due to Rust ownership

Safe non-trivial data dependencies/custom references?

丶灬走出姿态 提交于 2019-12-10 06:46:40
问题 One of the central features of Rust is the compile-time enforced safety of references, which is achieved though ownership mechanics and explicit lifetimes. Is it possible to implement 'custom' references that would benefit from the same? Consider the following example. We have an object that represents a graph. Assume that we can traverse the graph by referencing its edges, however, these references are implemented as custom indices rather then pointers to some memory. Such an index could be

How can I model a bidirectional map without annoying the borrow checker?

耗尽温柔 提交于 2019-12-09 16:17:56
问题 From Why can't I store a value and a reference to that value in the same struct? I learned that I cannot store a value and a reference in the same struct. The proposed solution is: The easiest and most recommended solution is to not attempt to put these items in the same structure together. By doing this, your structure nesting will mimic the lifetimes of your code. Place types that own data into a structure together and then provide methods that allow you to get references or objects

Why does the compiler tell me to consider using a `let` binding" when I already am?

核能气质少年 提交于 2019-12-09 13:37:49
问题 What is my error and how to fix it? fn get_m() -> Vec<i8> { vec![1, 2, 3] } fn main() { let mut vals = get_m().iter().peekable(); println!("Saw a {:?}", vals.peek()); } (playground) The compiler's error suggests "consider using a let binding" — but I already am: error[E0597]: borrowed value does not live long enough --> src/main.rs:6:45 | 6 | let mut vals = get_m().iter().peekable(); | ------- ^ temporary value dropped here while still borrowed | | | temporary value created here 7 | println!(

How can I replace the value inside a Mutex?

荒凉一梦 提交于 2019-12-08 19:04:08
问题 I have a Git repository hidden behind a Mutex : pub struct GitRepo { contents: Mutex<GitContents>, workdir: PathBuf, } I want to query it, but only a maximum of once: after it's been queried, I want to just use the results we got the first time. A repository has either a git2::Repository, or a vector of results. A Repository is Send but not Sync . enum GitContents { Before { repo: git2::Repository }, After { statuses: Git }, } struct Git { statuses: Vec<(PathBuf, git2::Status)>, } The

Why Rust prevents from multiple mutable references?

前提是你 提交于 2019-12-07 20:46:35
问题 Like in the topic, why Rust prevents from multiple mutable references? I have read chapter in rust-book, and I understand that when we have multi-threaded code we are secured from data races but let's look at this code: fn main() { let mut x1 = String::from("hello"); let r1 = &mut x1; let r2 = &mut x1; r1.insert(0, 'w'); } This code is not running simultaneously so there is no possibility for data races. What is more when I am creating new thread and I want to use variable from parent thread

How do I update a variable in a loop to a reference to a value created inside the loop?

ⅰ亾dé卋堺 提交于 2019-12-07 12:53:49
问题 I want to enter a loop with a variable n which is borrowed by the function. At each step, n takes a new value; when exiting the loop, the job is done, with the help of other variables, and n will never be used again. If I don't use references, I have something like this: fn test(n: Thing) -> usize { // stuff let mut n = n; for i in 1..10 { let (q, m) = n.do_something(...); n = m; // stuff with x } x } x is the result of some computation with q and m but it is an usize type and I didn't

How to iterate over mutable elements inside another mutable iteration over the same elements?

爷,独闯天下 提交于 2019-12-07 11:05:19
问题 I have an array of Element s and I want to iterate over it to do some stuff, then iterate over all Element s inside the loop to do something. There is a relation between elements so I want to iterate to all other elements to check something. The elements are mutable references for reasons. It's a bit broad, but I'm trying to be general (maybe I should not). struct Element; impl Element { fn do_something(&self, _e: &Element) {} } fn main() { let mut elements = [Element, Element, Element,

Destructuring a struct containing a borrow in a function argument

為{幸葍}努か 提交于 2019-12-07 03:13:13
问题 I am trying to implement a system that would use borrow checking/lifetimes in order to provide safe custom indices on a collection. Consider the following code: struct Graph(i32); struct Edge<'a>(&'a Graph, i32); impl Graph { pub fn get_edge(&self) -> Edge { Edge(&self, 0) } pub fn split(&mut self, Edge(_, edge_id): Edge) { self.0 = self.0 + edge_id; } pub fn join(&mut self, Edge(_, edge0_id): Edge, Edge(_, edge1_id): Edge) { self.0 = self.0 + edge0_id + edge1_id; } } fn main() { let mut

How to get mutable struct from HashMap?

安稳与你 提交于 2019-12-06 09:51:20
I have a hashmap for all my states, which is a HashMap<String, Rc<State>> , and I want to call the current state's member fn init(&mut self) . But I'm getting an error with the following code: ... if let Some(state) = self.states.get_mut(state_id) { (*state).init(); } ... Here's the error: src/main.rs:70:25: 70:33 error: cannot borrow immutable borrowed content as mutable src/main.rs:70 (*state).shutdown();` afaict from the documentation, the problem is that get_mut returns a mutable reference to the state, not a reference to a mutable state. So how would I get a reference to a mutable state?