lifetime

Mutable borrow in a loop

吃可爱长大的小学妹 提交于 2019-11-28 04:10:53
问题 I have the following code: struct Baz { x: usize, y: usize, } struct Bar { baz: Baz, } impl Bar { fn get_baz_mut(&mut self) -> &mut Baz { &mut self.baz } } struct Foo { bar: Bar, } impl Foo { fn foo(&mut self) -> Option<&mut Baz> { for i in 0..4 { let baz = self.bar.get_baz_mut(); if baz.x == 0 { return Some(baz); } } None } } Rust Playground It fails to compile with: error[E0499]: cannot borrow `self.bar` as mutable more than once at a time --> src/main.rs:23:23 | 23 | let baz = self.bar.get

“cannot infer an appropriate lifetime for pattern due to conflicting requirements” in `ref mut` pattern

别来无恙 提交于 2019-11-28 03:29:11
问题 struct RefWrap<'a> { wrap: &'a mut Option<String>, } impl<'a> RefWrap<'a> { fn unwrap(&mut self) -> &'a mut String { match *self.wrap { Some(ref mut s) => s, None => panic!(), } } } (Playground) As far as I understand, this code is correct (the returned reference really has the lifetime 'a . But Rust produces the following error: error[E0495]: cannot infer an appropriate lifetime for pattern due to conflicting requirements --> <anon>:8:18 | 8 | Some(ref mut s) => s, | ^^^^^^^^^ Using

How do I call a function that requires a 'static lifetime with a variable created in main?

别说谁变了你拦得住时间么 提交于 2019-11-28 02:05:44
I've got a struct defined that has a function which defines a static lifetime: impl MyStruct { pub fn doSomething(&'static self) { // Some code goes here } } I'm consuming it from main like so: fn main() { let obj = MyStruct {}; obj.doSomething(); } It's intended for the doSomething call to block and execute for the lifetime of the application. I'm running into issues with the lifetime checks where it's stating that it may outlive the main function, which seems strange to me as once main is complete the application should exit. Is there a way to achieve this? The naive way to do this is with a

Why does the Rust compiler request I constrain a generic type parameter's lifetime (error E0309)?

。_饼干妹妹 提交于 2019-11-27 22:37:08
Why does the Rust compiler emit an error requesting me to constrain the lifetime of the generic parameter in the following structure? pub struct NewType<'a, T> { x: &'a T, } error[E0309]: the parameter type `T` may not live long enough --> src/main.rs:2:5 | 2 | x: &'a T, | ^^^^^^^^ | = help: consider adding an explicit lifetime bound `T: 'a`... note: ...so that the reference type `&'a T` does not outlive the data it points at --> src/main.rs:2:5 | 2 | x: &'a T, | ^^^^^^^^ I can fix it by changing to pub struct NewType<'a, T> where T: 'a, { x: &'a T, } I don't understand why it is necessary to

How can this instance seemingly outlive its own parameter lifetime?

谁都会走 提交于 2019-11-27 18:49:56
Before I stumbled upon the code below, I was convinced that a lifetime in a type's lifetime parameter would always outlive its own instances. In other words, given a foo: Foo<'a> , then 'a would always outlive foo . Then I was introduced to this counter-argument code by @Luc Danton ( Playground ): #[derive(Debug)] struct Foo<'a>(std::marker::PhantomData<fn(&'a ())>); fn hint<'a, Arg>(_: &'a Arg) -> Foo<'a> { Foo(std::marker::PhantomData) } fn check<'a>(_: &Foo<'a>, _: &'a ()) {} fn main() { let outlived = (); let foo; { let shortlived = (); foo = hint(&shortlived); // error: `shortlived` does

Rust lifetime error expected concrete lifetime but found bound lifetime

主宰稳场 提交于 2019-11-27 16:04:42
I am having an issue working with lifetime parameters for structs. I am not 100% sure how to describe the problem, but I created a trivial case that shows my compile time error. struct Ref; struct Container<'a> { r : &'a Ref } struct ContainerB<'a> { c : Container<'a> } trait ToC { fn to_c<'a>(&self, r : &'a Ref) -> Container<'a>; } impl<'a> ToC for ContainerB<'a> { fn to_c(&self, r : &'a Ref) -> Container<'a> { self.c } } The error I am getting with this is test.rs:16:3: 18:4 error: method `to_c` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime

Why can the lifetimes not be elided in a struct definition?

泪湿孤枕 提交于 2019-11-27 16:04:10
struct Point { x: u32, y: u32, } struct Line<'a> { start: &'a Point, end: &'a Point, } Here, the only possible option for the start and end fields is to have a lifetime the same or longer than the Line variable that contains them. I can't even imagine how one will go about using a lifetime specifier to say that the fields have a shorter lifespan. Why do I have to explicitly specify a lifetime here? Is elision not possible in this situation and if so why not? When you define a struct, you aren't making a relation between the lifetime of the struct and the lifetime of the fields. As you point

Sharing a struct with trait objects as properties across threads

旧时模样 提交于 2019-11-27 15:54:10
I have the code below. With the commented out parts, it's working. When I uncomment the parts it does not compile anymore. How can I adjust the commented parts to make them work, i.e., I want to make threads access the expression tree simultaneously. When I try it, the compiler starts with errors about thread safeness. I read the Rust book and know C/C++, but didn't understood everything about Rust type system and semantics yet. use std::thread; use std::sync::Arc; pub trait Expr { fn run(&self) -> i32; } pub struct ConstantExpr { n: i32, } impl ConstantExpr { pub fn new(n: i32) -> Self { Self

How to declare a lifetime for a closure argument?

旧时模样 提交于 2019-11-27 15:02:34
I would like to declare a lifetime for a closure in Rust, but I can't find a way to add a lifetime declaration. use std::str::SplitWhitespace; pub struct ParserError { pub message: String, } fn missing_token(line_no: usize) -> ParserError { ParserError { message: format!("Missing token on line {}", line_no), } } fn process_string(line: &str, line_number: usize) -> Result<(), ParserError> { let mut tokens = line.split_whitespace(); match try!(tokens.next().ok_or(missing_token(line_number))) { "hi" => println!("hi"), _ => println!("Something else"), } // The following code gives "cannot infer

lifetime of a std::initializer_list return value

穿精又带淫゛_ 提交于 2019-11-27 14:18:49
GCC's implementation destroys a std::initializer_list array returned from a function at the end of the return full-expression. Is this correct? Both test cases in this program show the destructors executing before the value can be used: #include <initializer_list> #include <iostream> struct noisydt { ~noisydt() { std::cout << "destroyed\n"; } }; void receive( std::initializer_list< noisydt > il ) { std::cout << "received\n"; } std::initializer_list< noisydt > send() { return { {}, {}, {} }; } int main() { receive( send() ); std::initializer_list< noisydt > && il = send(); receive( il ); } I