lifetime

How to initialize a variable with a lifetime?

风格不统一 提交于 2019-11-29 13:22:32
I have following code and don't know how to get it working: fn new_int<'a>() -> &'a isize { &5 } fn main() { let x = new_int(); } Or another attempt: fn new_int<'a>() -> &'a isize { let a: &'a isize = &5; a } fn main() { let x = new_int(); } Paolo Falabella You can't. A lifetime parameter does not allow you to choose how long a value lives, it only allows you to communicate to the compiler that two or more references are "related" to the same memory and are expected to share the same lifetime. A function (like new_int in your case) can allocate memory in two ways: locally in an area (the stack

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:

Explicit lifetime declarations in trait objects held by structs

寵の児 提交于 2019-11-29 10:56:30
In the answer to this question there's a discussion of how to refer to trait objects held by structs which requires the following syntax: struct Bar<'a> { foo: &'a (Foo + 'a), } This is per RFC 438 Could I ask for more explanation of the double lifetime declaration? Levans said: You have to specify the lifetime two times : once for the lifetime of the reference, and once for the trait object itself, because traits can be implemented for references, and if the underlying object is a reference, you must specify its lifetime as well. I understand the notion of a lifetime for the reference in the

Mutable borrow in a loop

≡放荡痞女 提交于 2019-11-29 10:46:26
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_baz_mut(); | ^^^^^^^^ mutable borrow starts here in previous iteration of loop ... 29 | } | - mutable

Why would you ever use the same lifetimes for references in a struct?

给你一囗甜甜゛ 提交于 2019-11-29 09:55:32
This question is similar to When is it useful to define multiple lifetimes in a struct? , but hopefully different enough. The answer to that question is helpful but focuses on advantages of one approach (using distinct lifetimes for references in struct) but not on drawbacks (if any). This question, like that, is looking for guidance on how to choose lifetimes when creating structs. Call this the tied together version because x and y are required to have the same lifetime: struct Foo<'a> { x: &'a i32, y: &'a i32, } and call this the loose version because lifetimes can vary: struct Foo<'a, 'b>

Lifetime annotation for closure argument

落花浮王杯 提交于 2019-11-29 07:20:21
I'd like to make the following code compile: struct Provider {} impl Provider { fn get_string<'a>(&'a self) -> &'a str { "this is a string" } } fn main() { let provider = Provider{}; let mut vec: Vec<&str> = Vec::new(); // PROBLEM: how do I say that this reference s here // needs to live as long as vec? let fun = |s: &str| { vec.push(s); }; fun(provider.get_string()); } Playground link This is the compile error that I get: error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements --> src/main.rs:9:22 | 9 | let mut vec: Vec<&str> = Vec::new(); | ^^^^ | note: first, the

Rust function does not have static lifetime?

☆樱花仙子☆ 提交于 2019-11-29 06:52:50
I am trying to make this simple code compile: fn dox(x: u8) -> u8 { x*2 } fn main() { let cb: &'static (Fn(u8) -> u8) = &dox; } But it fails with Rust 1.9: x.rs:4:40: 4:43 error: borrowed value does not live long enough x.rs:4 let cb: &'static (Fn(u8) -> u8) = &dox; ^~~ note: reference must be valid for the static lifetime... x.rs:4:44: 5:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:43 x.rs:4 let cb: &'static (Fn(u8) -> u8) = &dox; x.rs:5 } error: aborting due to previous error How is it possible that a free function does not have static lifetime?

Full-expression boundaries and lifetime of temporaries [duplicate]

拈花ヽ惹草 提交于 2019-11-29 06:28:52
Possible Duplicate: C++: Life span of temporary arguments? It is said that temporary variables are destroyed as the last step in evaluating the full-expression, e.g. bar( foo().c_str() ); temporary pointer lives until bar returns, but what for the baz( bar( foo().c_str() ) ); is it still lives until bar returns, or baz return means full-expression end here, compilers I checked destruct objects after baz returns, but can I rely on that? Temporaries life until the end of the full expression in which they are created. A "full expression" is an expression that's not a sub-expression of another

What is the lifetime of a default argument temporary bound to a reference parameter?

时光总嘲笑我的痴心妄想 提交于 2019-11-29 06:20:44
I thought references only extend the lifetime of temporaries to the lifetime of the reference itself, but the output of the following snippet seems contradictory: #include <iostream> struct X{ ~X(){ std::cout << "Goodbye, cruel world!\n"; } }; X const& f(X const& x = X()){ std::cout << "Inside f()\n"; return x; } void g(X const& x){ std::cout << "Inside g()\n"; } int main(){ g(f()); } Live example. Output: Inside f() Inside g() Goodbye, cruel world! So it seems the temporary is destroyed after g() is called... what gives? The standard handles this in a special case in §12.2 [class.temporary] :

Is it allowed to call destructor explicitly followed by placement new on a variable with fixed lifetime?

a 夏天 提交于 2019-11-29 05:32:09
I know that calling destructor explicitly can lead to undefined behavior because of double destructor calling, like here: #include <vector> int main() { std::vector<int> foo(10); foo.~vector<int>(); return 0; // Oops, destructor will be called again on return, double-free. } But, what if we call placement new to "resurrect" the object? #include <vector> int main() { std::vector<int> foo(10); foo.~vector<int>(); new (&foo) std::vector<int>(5); return 0; } More formally: What will happen in C++ (I'm interested in both C++03 and C++11, if there is a difference) if I explicitly call a destructor