borrow-checker

Cannot move out of borrowed content when unwrapping

你说的曾经没有我的故事 提交于 2019-12-16 22:17:55
问题 This is the code I am trying to execute: fn my_fn(arg1: &Option<Box<i32>>) -> (i32) { if arg1.is_none() { return 0; } let integer = arg1.unwrap(); *integer } fn main() { let integer = 42; my_fn(&Some(Box::new(integer))); } (on the Rust playground) I get the following error: error[E0507]: cannot move out of borrowed content --> src/main.rs:5:19 | 5 | let integer = arg1.unwrap(); | ^^^^ cannot move out of borrowed content I see there is already a lot of documentation about borrow checker issues

Replacing values in Rust causing “cannot move out of borrowed content” [duplicate]

限于喜欢 提交于 2019-12-14 04:04:12
问题 This question already has answers here : How can I swap in a new value for a field in a mutable reference to a structure? (2 answers) Closed last year . I'm trying to build a graphics engine that works with the fairly common two-buffer pattern. One buffer ( current_buffer ) is displayed while the next ( next_buffer ) is prepared, then the next buffer is moved into the current buffer, and is subsequently repopulated by a new buffer, repeating. I know there are a lot of other questions about

Why does a call to `fn pop(&mut self) -> Result<T, &str>` continue to borrow my data structure?

橙三吉。 提交于 2019-12-13 15:11:24
问题 I am developing some basic data structures to learn the syntax and Rust in general. Here is what I came up with for a stack: #[allow(dead_code)] mod stack { pub struct Stack<T> { data: Vec<T>, } impl<T> Stack<T> { pub fn new() -> Stack<T> { return Stack { data: Vec::new() }; } pub fn pop(&mut self) -> Result<T, &str> { let len: usize = self.data.len(); if len > 0 { let idx_to_rmv: usize = len - 1; let last: T = self.data.remove(idx_to_rmv); return Result::Ok(last); } else { return Result::Err

How to use (unsafe) aliasing?

早过忘川 提交于 2019-12-13 13:11:17
问题 Rust has strict aliasing rules. But can I work around them if "I know what I'm doing"? I'm trying to convert to Rust a C function that performs a complicated operation by reading from input buffer and writing to a destination buffer, but it has a clever optimization that allows the input and output buffer to be the same: foo(src, dst); // result is written to dst foo(buf, buf); // legal in C, does the operation in-place For the sake of the question let's say it's something like: void inplace

What is the difference between dereferencing a raw pointer to a String and a raw pointer to an i32?

你离开我真会死。 提交于 2019-12-13 03:49:45
问题 fn func(s: *mut String, a: *mut i32) -> usize { println!("{}", unsafe { *s }); println!("{}", unsafe { *a }); unsafe { (*s).len() } } fn main() { let mut s = String::from("hello"); let mut a = 10; func(&mut s, &mut a); } The above code fails with the error: error[E0507]: cannot move out of dereference of raw pointer --> src/main.rs:2:29 | 2 | println!("{}", unsafe { *s }); | ^^ cannot move out of dereference of raw pointer Why does it happen for String and not for i32 ? Why is it complaining

“cannot move out of borrowed content” when replacing a struct field [duplicate]

吃可爱长大的小学妹 提交于 2019-12-13 03:23:26
问题 This question already has an answer here : Cannot move out of borrowed content / cannot move out of behind a shared reference (1 answer) Closed 11 months ago . Consider this example: struct Item { x: u32, } impl Item { pub fn increment(self, amount: u32) -> Self { Item { x: self.x + amount } } } struct Container { item: Item, } impl Container { pub fn increment_item(&mut self, amount: u32) { // This line causes "cannot move out of borrowed content" self.item = self.item.increment(amount); } }

How do I mutate a structure I am looping over?

依然范特西╮ 提交于 2019-12-12 15:14:10
问题 This question is motivated by this CodinGame puzzle. I am implementing a basic pathfinding algorithm using Dijkstra's method. It uses a boundary HashMap and a finished HashMap to hold pathfinding-related node info. In a particular loop, I find the highest-valued node in boundary , remove the node, add the node to finished , and add/update the node's neighbors' info in boundary . Attempting to mutate boundary while looping over it is making Rust's borrow checker queasy, but the logic of the

Why is it possible to return a mutable reference to a literal from a function?

99封情书 提交于 2019-12-12 12:28:17
问题 The current edition of The Rustonomicon has this example code: use std::mem; pub struct IterMut<'a, T: 'a>(&'a mut [T]); impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { let slice = mem::replace(&mut self.0, &mut []); if slice.is_empty() { return None; } let (l, r) = slice.split_at_mut(1); self.0 = r; l.get_mut(0) } } I'm confused about this line in particular: let slice = mem::replace(&mut self.0, &mut []); // ^^^^^^^ How does this

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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 08:37:02
问题 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 |

Rust loop on HashMap while borrowing self

北城以北 提交于 2019-12-12 05:26:11
问题 I have a Element struct that implements an update method which takes a tick duration. The struct contains a vector of components. These components are allowed to modify the element on an update. I'm getting a borrow error here and I'm not sure what to do. I tried fixing it with a block, but the block doesn't seems to satisfy the borrow checker. use std::collections::HashMap; use std::time::Duration; pub struct Element { pub id: String, components: HashMap<String, Box<Component>>, } pub trait