lifetime

Why does the borrow from `HashMap::get` not end when the function returns?

我是研究僧i 提交于 2019-12-02 08:28:01
Here is emulation of my problem, when a borrow ends too late use std::collections::HashMap; struct Item { capacity: u64 } struct Petrol { name: String, fuel: HashMap<&'static str, Item> } fn buy_gaz(p: &mut Petrol) { match p.fuel.get("gaz") { Some(gaz) => { fire_petrol(p); } None => () } } fn fire_petrol(p: &mut Petrol) { println!("Boom!"); p.fuel.remove("gaz"); p.fuel.remove("benzin"); } fn main() { let mut bt = Petrol { name: "Britii Petrovich".to_string(), fuel: HashMap::new() }; bt.fuel.insert("gaz", Item { capacity: 1000 }); bt.fuel.insert("benzin", Item { capacity: 5000 }); buy_gaz(&mut

Binding does not live long enough when storing a reference to a vector item in a hash map

徘徊边缘 提交于 2019-12-02 07:55:55
I'm new at Rust and still struggling with the borrow checker and getting lifetimes right. Here's a simple struct I've started to build - it stores collections of command-line argument like things (which can be represented by a --string or a -c or both): struct OptionMap<'a, T: 'a> { name: HashMap<String, &'a T>, short_name: HashMap<char, &'a T>, options: Vec<T> } impl<'a, T: 'a> OptionMap<'a, T> { pub fn new() -> OptionMap<'a, T> { OptionMap { name: HashMap::new(), short_name: HashMap::new(), options: Vec::new() } } pub fn register(&mut self, name: &OptionName, option: T) { if name.name.is

Rust: error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements

久未见 提交于 2019-12-02 07:32:30
This is the minimal code: struct Node<T> { item: T, next: Link<T>, } type Link<T> = Option<Box<Node<T>>>; pub struct IterMut<'a, T>(&'a mut Link<T>); impl<'a, T> Iterator for IterMut<'a, T> { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.0.as_mut().map(|boxed_node| { self.0 = &mut boxed_node.next; &mut boxed_node.item }) } } As far as I understand, there should be no problem. I have done a lot of searching, but no way. error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements --> src/lib.rs:13:16 | 13 | self.0.as_mut().map(|boxed

error: cannot infer an appropriate lifetime for autoref due to conflicting requirements [E0495]

≯℡__Kan透↙ 提交于 2019-12-02 06:50:42
First of all: I am fully aware of this post: Cannot infer appropriate lifetime for autoref in Iterator impl and that the problem is probably similar to mine. However, I can't get it working with the knowledge of this thread. The code: use std::str::Chars; use super::token::*; use super::token_stream::TokenStream; pub struct Lexer<'a> { input: Chars<'a>, buffer: String, cur_char: char } impl<'a> Lexer<'a> { pub fn new(iterator: Chars<'a>) -> Lexer { let mut lexer = Lexer { input: iterator, buffer: String::new(), cur_char: '\0' }; lexer.consume_next(); lexer } pub fn new_from_str(content : &str)

Is there a way to use locked standard input and output in a constructor to live as long as the struct you're constructing?

余生长醉 提交于 2019-12-02 05:41:45
I'm building a PromptSet that can ask a series of questions in a row. For testing reasons, it allows you to pass a reader and writer instead of using stdin & stdout directly. Because stdin and stdout are the common use case, I would like to create a default "constructor" that allows the user to produce a PromptSet<StdinLock, StdoutLock> without needing any parameters. Here's the code so far: use std::io::{self, BufRead, StdinLock, StdoutLock, Write}; pub struct PromptSet<R, W> where R: BufRead, W: Write, { pub reader: R, pub writer: W, } impl<R, W> PromptSet<R, W> where R: BufRead, W: Write, {

How do I form a slice from a HashSet?

余生颓废 提交于 2019-12-02 04:17:31
问题 A struct is defined as: struct Node { set: HashSet<usize>, // other fields omitted } I have to implement a function for a trait (compatibility issues) which needs to return all elements in the set as a slice. I am aware of something like the following function won't work: impl Node { pub fn set_slice(&self) -> &[usize] { let elems: Vec<_> = self.set.iter().cloned().collect(); &elems[..] } } The problem is: error[E0597]: `elems` does not live long enough --> src/main.rs:11:10 | 11 | &elems[..]

Why do I get the error “cannot borrow x as mutable more than once”?

社会主义新天地 提交于 2019-12-02 03:55:01
I'm implementing a parser in Rust. I have to update the index for the lookahead, but when I call self.get() after self.current() I get an error: cannot borrow *self as mutable more than once at a time It's confusing since I'm new to Rust. #[derive(Debug)] pub enum Token { Random(String), Undefined(String), } struct Point { token: Vec<Token>, look: usize, } impl Point { pub fn init(&mut self){ while let Some(token) = self.current(){ println!("{:?}", token); let _ = self.get(); } } pub fn current(&mut self) -> Option<&Token> { self.token.get(self.look) } pub fn get(&mut self) -> Option<&Token> {

How do I form a slice from a HashSet?

落爺英雄遲暮 提交于 2019-12-02 03:40:11
A struct is defined as: struct Node { set: HashSet<usize>, // other fields omitted } I have to implement a function for a trait (compatibility issues) which needs to return all elements in the set as a slice. I am aware of something like the following function won't work: impl Node { pub fn set_slice(&self) -> &[usize] { let elems: Vec<_> = self.set.iter().cloned().collect(); &elems[..] } } The problem is: error[E0597]: `elems` does not live long enough --> src/main.rs:11:10 | 11 | &elems[..] | ^^^^^ borrowed value does not live long enough 12 | } | - borrowed value only lives until here |

Why is it possible to have multiple mutable references with static lifetime in same scope

亡梦爱人 提交于 2019-12-02 02:49:38
问题 Why can I have multiple mutable references to a static type in the same scope? My code: static mut CURSOR: Option<B> = None; struct B { pub field: u16, } impl B { pub fn new(value: u16) -> B { B { field: value } } } struct A; impl A { pub fn get_b(&mut self) -> &'static mut B { unsafe { match CURSOR { Some(ref mut cursor) => cursor, None => { CURSOR= Some(B::new(10)); self.get_b() } } } } } fn main() { // first creation of A, get a mutable reference to b and change its field. let mut a = A {}

Why does cloning data inside a closure not prevent the error “closure may outlive the current function”?

一曲冷凌霜 提交于 2019-12-02 02:05:51
I built a GTK application with gtk-rs. When I build the main window, I want to use some dynamic parameters such as window height. I created a struct which contains all such settings and want to use this as an input parameter for the function building the UI: fn main() { let application = gtk::Application::new(Some("id"), Default::default()) .expect("Initialization failed..."); let config = Config {width: 100., height: 100.}; application.connect_activate(|app| { build_ui(app, config.clone()); }); // Use config further application.run(&args().collect::<Vec<_>>()); } #[derive(Debug, Clone)] pub