borrow-checker

Why Rust prevents from multiple mutable references?

不打扰是莪最后的温柔 提交于 2019-12-06 07:31:18
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 in a new thread I have to move it so only new thread is an owner of the parent variable. The only

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

不羁的心 提交于 2019-12-06 06:13:40
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>) -> Option<Result> { Some(Result { str: "whatever string".to_string(), }) } However, I'm not sure how to

Is it possible to share data with threads without any cloning?

匆匆过客 提交于 2019-12-05 23:02:37
问题 When I'm delegating work to threads I often have a piece of data that will outlive all of the threads, such as numbers in the following example: use std::thread; fn main() { let numbers = vec![1, 2, 3]; let thread_a = thread::spawn(|| println!("{}", numbers.len())); let thread_b = thread::spawn(|| println!("{}", numbers.len())); thread_a.join().unwrap(); thread_b.join().unwrap(); } It's not modified anywhere, and because of the join s, it's guaranteed that the threads are done using it.

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

天涯浪子 提交于 2019-12-05 18:07:21
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, Element]; for e in &mut elements { // Do stuff... for f in &mut elements { e.do_something(f); } } } As

Destructuring a struct containing a borrow in a function argument

Deadly 提交于 2019-12-05 06:09:11
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 graph = Graph(0); let edge = graph.get_edge(); graph.split(edge) } References to the graph borrowed by the

Borrowed value does not live long enough when creating a Vec

*爱你&永不变心* 提交于 2019-12-04 11:28:22
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_path : &str) -> Vec<&str> { let v = fs::readdir(&Path::new(action_dir_path)) .unwrap() .iter() .map(|&x|

How to assign to the variable used in match expression inside a match branch?

南笙酒味 提交于 2019-12-04 05:29:09
问题 I'm trying to implement a general function join() that can work on any iterator of iterators. I have a problem with the borrow checker in a match expression inside the next() method implementation. Here is a simplified version of my code: pub struct Join<I> where I: Iterator, I::Item: IntoIterator, { outer_iter: I, inner_iter: Option<<I::Item as IntoIterator>::IntoIter>, } impl<I> Join<I> where I: Iterator, I::Item: IntoIterator, { pub fn new(mut iter: I) -> Join<I> { let inner_iter = iter

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

♀尐吖头ヾ 提交于 2019-12-04 03:41:59
问题 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

Borrow-check error with variable not living long enough in nested lambda

妖精的绣舞 提交于 2019-12-04 03:38:48
I am getting an error inside a nested lambda. let rows = vec![ vec![3, 6, 2, 8, 9, 0], vec![0, 0, 1, 4, 5, 1], ]; let pair_sums = rows.iter() .flat_map(|row| { (0 ..= row.len()).map(|i| row[i] + row[i + 1]) }) .collect::<Vec<_>>(); println!("{:?}", pair_sums); error[E0597]: `row` does not live long enough --> src/main.rs:9:40 | 9 | (0..row.len() - 1).map(|i| row[i] + row[i + 1]) | --- ^^^ does not live long enough | | | capture occurs here 10 | }) | - borrowed value only lives until here 11 | .collect::<Vec<_>>(); | - borrowed value needs to live until here I can sort of see why this is

Get an enum field from a struct: cannot move out of borrowed content

筅森魡賤 提交于 2019-12-04 00:36:27
问题 I'm new to Rust and trying to wrap my head around the ownership/borrowing concept. Now I have reduced my code to this minimal code sample that gives a compile error. pub struct Display { color: Color, } pub enum Color { Blue = 0x1, Red = 0x4, } impl Display { fn get_color_value(&self) -> u16 { self.color as u16 } } src/display.rs:12:9: 12:13 error: cannot move out of borrowed content src/display.rs:12 self.color as u16 ^~~~ error: aborting due to previous error Could not compile. I'm still in