lifetime

Lifetimes in Rust

百般思念 提交于 2019-11-29 20:50:57
Occasionally I've found myself wanting to write functions that can be called in either of two ways: // With a string literal: let lines = read_file_lines("data.txt"); // With a string pointer: let file_name = ~"data.txt"; let lines = read_file_lines(file_name); My first guess was to use a borrowed pointer ( &str ) for the parameter type, but when that didn't work (it only allowed me to use @str and ~str ), I tried the following (by copying the Rust libraries), which did work. fn read_file_lines<'a>(path: &'a str) -> ~[~str] { let read_result = file_reader(~Path(path)); match read_result { Ok

How do I efficiently build a vector and an index of that vector while processing a data stream?

柔情痞子 提交于 2019-11-29 19:35:06
问题 I have a struct Foo : struct Foo { v: String, // Other data not important for the question } I want to handle a data stream and save the result into Vec<Foo> and also create an index for this Vec<Foo> on the field Foo::v . I want to use a HashMap<&str, usize> for the index, where the keys will be &Foo::v and the value is the position in the Vec<Foo> , but I'm open to other suggestions. I want to do the data stream handling as fast as possible, which requires not doing obvious things twice.

Contradictory “missing lifetime specifier” error on owned value [duplicate]

妖精的绣舞 提交于 2019-11-29 18:21:13
This question already has an answer here: Getting 'Missing Lifetime specifier' error 1 answer Why do I get “missing lifetime specifier” or “wrong number of type arguments” when implementing a trait for a struct? 1 answer I wrote code to model the following structure, where a node has a reference to its parent node: struct Node<'a> { parent: &'a Node, } impl<'a> Node<'a> { fn new(parent: &'a Node) -> Node { Node { parent } } } I thought with the lifetime parameter on the parent attribute and on the parent parameter in the new function it is made clear that the value behind the reference to

Who borrowed a variable?

早过忘川 提交于 2019-11-29 17:36:57
问题 I'm fighting with the borrow checker. I have two similar pieces of code, one working as I expect, and the other not. The one that works as I expect: mod case1 { struct Foo {} struct Bar1 { x: Foo, } impl Bar1 { fn f<'a>(&'a mut self) -> &'a Foo { &self.x } } // only for example fn f1() { let mut bar = Bar1 { x: Foo {} }; let y = bar.f(); // (1) 'bar' is borrowed by 'y' let z = bar.f(); // error (as expected) : cannot borrow `bar` as mutable more // than once at a time [E0499] } fn f2() { let

Extending borrow lifetimes in rust

淺唱寂寞╮ 提交于 2019-11-29 17:19:34
I'm trying to parse a series to tokentrees, but when I try to implement my parsing trait I get an error related to reference lifetimes. I thought creating a boxed version would move around any issues with reference counts or lifetimes. The code is as follows. impl Parse for TokenTree { fn parse(&mut self) -> Tree { match self.clone() { TtDelimited(_, y) => { let mut y2 = box (*y).clone(); match y2.delim { token::DelimToken::Paren => y2.parse(), _ => panic!("not done yet"), } } TtToken(_, t) => E(t), _ => panic!("not done yet"), } } } the errors I get make the issue clear, but I can't find any

variable does not live long enough when storing a csv::DecodedRecords iterator

荒凉一梦 提交于 2019-11-29 16:36:44
I'm trying to create an iterator trait that provides a specific type of resource, so I can implement multiple source types. I'd like to create a source for reading from a CSV file, a binary etc.. I'm using the rust-csv library for deserializing CSV data: #[derive(RustcDecodable)] struct BarRecord { bar: u32 } trait BarSource : Iterator {} struct CSVBarSource { records: csv::DecodedRecords<'static, std::fs::File, BarRecord>, } impl CSVBarSource { pub fn new(path: String) -> Option<CSVBarSource> { match csv::Reader::from_file(path) { Ok(reader) => Some(CSVBarSource { records: reader.decode() }),

Extend lifetime of a variable for thread

▼魔方 西西 提交于 2019-11-29 16:17:28
I am reading a string from a file, splitting it by lines into a vector and then I want to do something with the extracted lines in separate threads. Like this: use std::fs::File; use std::io::prelude::*; use std::thread; fn main() { match File::open("data") { Ok(mut result) => { let mut s = String::new(); result.read_to_string(&mut s); let k : Vec<_> = s.split("\n").collect(); for line in k { thread::spawn(move || { println!("nL: {:?}", line); }); } } Err(err) => { println!("Error {:?}",err); } } } Of course this throws an error, because s will go out of scope before the threads are started: s

How to prevent a value from being moved?

血红的双手。 提交于 2019-11-29 16:11:51
I'm having a lot of fun trying to solve the robot simulator Exercism exercise , but I'm facing a value moving problem for which I don't seem to be able to come up with an elegant solution: impl Robot { pub fn new(x: isize, y: isize, d: Direction) -> Self { Robot { position: Coordinate { x: x, y: y }, direction: d } } pub fn turn_right(mut self) -> Self { match self.direction { // ... }; self } pub fn turn_left(mut self) -> Self { match self.direction { // ... }; self } pub fn advance(mut self) -> Self { match self.direction { // ... }; self } pub fn instructions(self, instructions: &str) ->

What is the difference between '&self' and '&'a self'?

时间秒杀一切 提交于 2019-11-29 15:09:25
I recently had an error which was simply resolved by changing impl<'a> Foo<'a> { fn foo(&'a self, path: &str) -> Boo<'a> { /* */ } } to impl<'a> Foo<'a> { fn foo(&self, path: &str) -> Boo { /* */ } } which did not make sense according to my understanding, as I thought that the second version is exactly the same as the first with applied lifetime elision. In case we introduce a new lifetime for the method this seems to be the case according this example from the nomicon . fn get_mut(&mut self) -> &mut T; // elided fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded So what are the

How to return a future combinator with `&self`

点点圈 提交于 2019-11-29 14:43:27
I have this piece of code: impl ArcService for (Box<MiddleWare<Request>>, Box<ArcService>) { fn call(&self, req: Request, res: Response) -> Box<Future<Item = Response, Error = Error>> { box self.0.call(req).and_then(move |req| self.1.call(req, res)) } } pub trait ArcService: Send + Sync { fn call(&self, req: Request, res: Response) -> Box<Future<Item = Response, Error = Error>>; } pub trait MiddleWare<T>: Sync + Send { fn call<'a>(&'a self, param: T) -> Box<Future<Item = T, Error = Error> + 'a>; } type MiddleWareFuture<'a, I> = Box<Future<Item = I, Error = Error> + 'a>; impl MiddleWare<Request