borrow-checker

Implementing a “cautious” take_while using Peekable

我与影子孤独终老i 提交于 2019-11-28 08:00:09
问题 I'd like to use Peekable as the basis for a new cautious_take_while operation that acts like take_while from IteratorExt but without consuming the first failed item. (There's a side question of whether this is a good idea, and whether there are better ways to accomplish this goal in Rust -- I'd be happy for hints in that direction, but mostly I'm trying to understand where my code is breaking). The API I'm trying to enable is basically: let mut chars = "abcdefg.".chars().peekable(); let abc :

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

試著忘記壹切 提交于 2019-11-28 07:45:18
问题 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:

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

谁都会走 提交于 2019-11-28 07:21:20
问题 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

How can I reborrow a mutable reference without passing it to a function?

人走茶凉 提交于 2019-11-28 03:47:00
问题 I have found a case where manually inlining a function changes the way the borrow-checker treats it, such that it no longer compiles. Presumably it is relying on the information in the function signature. How can I provide this information in the inlined version? How I think it's working Let 'a and 'b be lifetimes with 'a shorter than 'b (which can be written 'b: 'a ). Suppose I have a p: &'b mut f32 . I can borrow p briefly (with &mut p ) to obtain q: &'a mut &'b mut f32 . Have I correctly

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

时光毁灭记忆、已成空白 提交于 2019-11-28 03:28:23
问题 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

How do I add references to a container when the borrowed values are created after the container?

久未见 提交于 2019-11-28 01:51:46
For reasons related to code organization, I need the compiler to accept the following (simplified) code: fn f() { let mut vec = Vec::new(); let a = 0; vec.push(&a); let b = 0; vec.push(&b); // Use `vec` } The compiler complains error: `a` does not live long enough --> src/main.rs:8:1 | 4 | vec.push(&a); | - borrow occurs here ... 8 | } | ^ `a` dropped here while still borrowed | = note: values in a scope are dropped in the opposite order they are created error: `b` does not live long enough --> src/main.rs:8:1 | 6 | vec.push(&b); | - borrow occurs here 7 | // Use `vec` 8 | } | ^ `b` dropped

Why are borrows of struct members allowed in &mut self, but not of self to immutable methods?

て烟熏妆下的殇ゞ 提交于 2019-11-27 19:24:29
问题 If I have a struct that encapsulates two members, and updates one based on the other, that's fine as long as I do it this way: struct A { value: i64 } impl A { pub fn new() -> Self { A { value: 0 } } pub fn do_something(&mut self, other: &B) { self.value += other.value; } pub fn value(&self) -> i64 { self.value } } struct B { pub value: i64 } struct State { a: A, b: B } impl State { pub fn new() -> Self { State { a: A::new(), b: B { value: 1 } } } pub fn do_stuff(&mut self) -> i64 { self.a.do

Borrow checker and function arguments in Rust, correct or over zealous? [duplicate]

邮差的信 提交于 2019-11-27 15:53:21
This question already has an answer here: Cannot borrow as immutable because it is also borrowed as mutable in function arguments 1 answer When a mutable argument is passed as a function argument, the borrow checker doesn't allow this to be used to construct other arguments, even when those arguments clone values without holding a reference. While assigning variables outside the function is always an option 1 , logically this seems over zealous and something the borrow checker could take into account. Is this working as intended or something that should be resolved? #[derive(Debug)] struct

Can't borrow File from &mut self (error msg: cannot move out of borrowed content)

元气小坏坏 提交于 2019-11-27 15:00:49
use std::fs::File; use std::io::Read; pub struct Foo { maybe_file: Option<File>, } impl Foo { pub fn init(&mut self) { self.maybe_file = Some(File::open("/proc/uptime").unwrap()); } pub fn print(&mut self) { let mut file = self.maybe_file.unwrap(); let mut s = String::new(); file.read_to_string(&mut s).unwrap(); println!("Uptime: {}", s); } } fn main() {} Compiling this will give me: error[E0507]: cannot move out of borrowed content --> src/main.rs:14:24 | 14 | let mut file = self.maybe_file.unwrap(); | ^^^^ cannot move out of borrowed content Why is this happening? What do I do to solve it?

Why does refactoring by extracting a method trigger a borrow checker error?

邮差的信 提交于 2019-11-27 09:46:20
The architecture of my networking application can be stripped down to the following: use std::collections::HashMap; /// Represents remote user. Usually has fields, /// but we omit them for the sake of example. struct User; impl User { /// Send data to remote user. fn send(&mut self, data: &str) { println!("Sending data to user: \"{}\"", data); } } /// A service that handles user data. /// Usually has non-trivial internal state, but we omit it here. struct UserHandler { users: HashMap<i32, User>, // Maps user id to User objects. counter: i32 // Represents internal state } impl UserHandler { fn