borrow-checker

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

匆匆过客 提交于 2019-11-29 14:53:06
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.children { let mut child = self.processes.get_mut(child_name).expect("Child not found."); child.parent

“cannot move out of variable because it is borrowed” when rotating variables

这一生的挚爱 提交于 2019-11-29 14:11:38
I am writing a program that writes to a file and rotates the file it's writing to every now and then. When I check to rotate the file, I can't seem to change the file since it is borrowed by my struct. Even if I drop the instance of the struct, I can't seem to regain ownership of the file to rename it. Here is my example : use std::fs::File; use std::io::{Write}; use std::mem::{drop}; pub struct FileStruct<W: Write> { pub writer: Option<W>, } impl <W: Write> FileStruct<W> { pub fn new(writer: W) -> FileStruct<W> { FileStruct { writer: Some(writer), } } } fn main() { let mut file = File::create

How can I modify self in a closure called from a member function?

假如想象 提交于 2019-11-29 13:46:18
I am trying to calculate legal chess moves and am having problems satisfying the borrow checker. I have a struct Chess that implements these methods (non-important code replaced by ... ): // internal iterator over (possibly not legal) moves fn get_moves<F>(&self, func: F) where F: Fn(/* ... */), { func(/* ... */); // move 1 func(/* ... */); // move 2 func(/* ... */); // etc... } fn is_legal_move(&mut self) -> bool { // notice this takes a mutable self. For performance // reasons, the move is made, legality is checked, then I // undo the move, so it must be mutable to be able to move pieces

Borrow checker doesn't realize that `clear` drops reference to local variable

这一生的挚爱 提交于 2019-11-29 13:10:26
The following code reads space-delimited records from stdin, and writes comma-delimited records to stdout. Even with optimized builds it's rather slow (about twice as slow as using, say, awk). use std::io::BufRead; fn main() { let stdin = std::io::stdin(); for line in stdin.lock().lines().map(|x| x.unwrap()) { let fields: Vec<_> = line.split(' ').collect(); println!("{}", fields.join(",")); } } One obvious improvement would be to use itertools to join without allocating a vector (the collect call causes an allocation). However, I tried a different approach: fn main() { let stdin = std::io:

Unable to pipe to or from spawned child process more than once

别来无恙 提交于 2019-11-29 09:50:17
I want to be able to use Rust to spawn a child shell, then repeatedly pass it arbitrary commands and process their outputs. I have found plenty of examples online showing me how to pass a single command and receive its single output, but I can't seem to be able to do it repeatedly. For instance, the following code hangs on the line after the comment. (I imagine maybe read_to_string() is blocking until it receives stdout from the child process, but if so I don't understand why that output isn't forthcoming..) let mut child_shell = match Command::new("/bin/bash") .stdin(Stdio::piped()) .stdout

Is this error due to the compiler's special knowledge about RefCell?

空扰寡人 提交于 2019-11-29 06:27:29
fn works<'a>(foo: &Option<&'a mut String>, s: &'a mut String) {} fn error<'a>(foo: &RefCell<Option<&'a mut String>>, s: &'a mut String) {} let mut s = "hi".to_string(); let foo = None; works(&foo, &mut s); // with this, it errors // let bar = RefCell::new(None); // error(&bar, &mut s); s.len(); If I put in the two lines with the comment, the following error occurs: error[E0502]: cannot borrow `s` as immutable because it is also borrowed as mutable --> <anon>:16:5 | 14 | error(&bar, &mut s); | - mutable borrow occurs here 15 | 16 | s.len(); | ^ immutable borrow occurs here 17 | } | - mutable

What's the correct way to implement the equivalent of multiple mutable (statically allocated, statically dispatched, etc.) callbacks in Rust?

此生再无相见时 提交于 2019-11-28 14:25:54
I have the following example code, which is the standard basis of event-driven APIs in other programming languages, but in Rust the borrow checker blocks it with "cannot borrow p1 as mutable more than once at a time": struct Pen { color_cmyk: u32, ink: usize, } impl Pen { pub fn new() -> Pen { Pen { color_cmyk: 0x80800000, ink: 20000, } } pub fn write(&mut self, text: &str) -> bool { if self.ink < text.len() { return false; } self.ink -= text.len(); true } } fn main() { println!("Hello, world !"); let mut p1 = Pen::new(); p1.write("Hello"); println!("ink: {}, color: {}", p1.ink, p1.color_cmyk)

“borrowed value does not live long enough” when using as_slice()

点点圈 提交于 2019-11-28 13:22:24
I ran into an error: extern crate rustc_serialize; // 0.3.24 use rustc_serialize::base64::{self, FromBase64, ToBase64}; fn main() { let a: [u8; 30] = [0; 30]; let b = a.from_base64().unwrap().as_slice(); println!("{:?}", b); } The error: error[E0597]: borrowed value does not live long enough --> src/main.rs:7:13 | 7 | let b = a.from_base64().unwrap().as_slice(); | ^^^^^^^^^^^^^^^^^^^^^^^^ - temporary value dropped here while still borrowed | | | temporary value does not live long enough 8 | println!("{:?}", b); 9 | } | - temporary value needs to live until here | = note: consider using a `let`

Returning a RWLockReadGuard independently from a method

夙愿已清 提交于 2019-11-28 09:47:05
问题 I have an object of type Arc<RwLock<SessionData>> And I have a method that is supposed to take some kind of reference to SessionData fn some_method(session: ...) I'm using Rocket (a web-framework for Rust), and I can't directly invoke the method, because it is invoked by Rocket. However, I can provide it with an implementation that creates an object that will be passed to the handler. It looks a bit like this: impl<'a, 'r> request::FromRequest<'a, 'r> for SomeType { type Error = (); fn from

How do I pass modified string parameters?

我们两清 提交于 2019-11-28 09:26:10
问题 I'm on chapter 12 of The Rust Programming Language, where a case insensitive line search is implemented. It doesn't make sense to me to implement the same logic twice, so I figured if I just called the case sensitive search function with the parameters converted to lower case, that might work. It did not. This is my non working code: fn main() { let a = search("Waldo", "where in\nthe world\nis Waldo?"); let b = search("waldo", "where in\nthe world\nis Waldo?"); let c = search_case_insensitive