lifetime

Is it possible to have a struct which contains a reference to a value which has a shorter lifetime than the struct?

雨燕双飞 提交于 2019-11-28 14:39:09
Here is a simplified version of what I want to archive: struct Foo<'a> { boo: Option<&'a mut String>, } fn main() { let mut foo = Foo { boo: None }; { let mut string = "Hello".to_string(); foo.boo = Some(&mut string); foo.boo.unwrap().push_str(", I am foo!"); foo.boo = None; } // string goes out of scope. foo does not reference string anymore } // foo goes out of scope This is obviously completely safe as foo.boo is None once string goes out of scope. Is there a way to tell this to the compiler? This is obviously completely safe What is obvious to humans isn't always obvious to the compiler;

Thread references require static lifetime?

不羁的心 提交于 2019-11-28 14:26:17
While it makes sense intuitively that references passed to spawned threads need to have static lifetimes, I'm unclear about what exactly is making the following code not compile: use std::sync::Arc; use std::sync::Mutex; struct M; fn do_something(m : Arc<Mutex<&M>>) { println!("Ha, do nothing!"); } fn main() { let a = M; { let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a)); for i in 0..2 { let c_clone = c.clone(); ::std::thread::spawn(move || do_something(c_clone)); } } } Compiling this small program gives the following error: $ rustc -o test test.rs test.rs:13:55: 13:56 error: `a` does not

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

蓝咒 提交于 2019-11-28 12:35:03
问题 This question already has answers 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) Closed 12 months ago . 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

Extend lifetime of variable

纵然是瞬间 提交于 2019-11-28 12:33:34
I'm trying to return a slice from a vector which is built inside my function. Obviously this doesn't work because v 's lifetime expires too soon. I'm wondering if there's a way to extend v 's lifetime. I want to return a plain slice, not a vector. pub fn find<'a>(&'a self, name: &str) -> &'a[&'a Element] { let v: Vec<&'a Element> = self.iter_elements().filter(|&elem| elem.name.borrow().local_name == name).collect(); v.as_slice() } You can't forcibly extend a value's lifetime; you just have to return the full Vec . If I may ask, why do you want to return the slice itself? It is almost always

How do I bound a generic type with a trait that requires a lifetime parameter if I create the reference inside the function?

烂漫一生 提交于 2019-11-28 12:30:17
I want to implement a generic fibonacci function that works with any type implementing Zero , One , and AddAssign . I first implemented a version that works fine, but is specialized for num::BigUint ( see on play.rust-lang.org ). I than came up with the following generic implementation ( see on play.rust-lang.org ): extern crate num; use num::{One, Zero}; use std::mem::swap; use std::ops::AddAssign; fn fib<T: Zero + One + AddAssign<&T>>(n: usize) -> T { let mut f0 = Zero::zero(); let mut f1 = One::one(); for _ in 0..n { f0 += &f1; swap(&mut f0, &mut f1); } f0 } This doesn't compile: error

Java scope and lifetime of variable

僤鯓⒐⒋嵵緔 提交于 2019-11-28 12:12:32
问题 I wrote the following program to display all prime numbers between 2 and 50 (inclusive). The program ran as intended but when I reexamined the code I wondered why it had not failed. The if statement can change the value of the isprime variable. However, is this change not forgotten once the inner for code block {} is left? This would mean that isprime would remain true and all numbers would be displayed. class Prime { public static void main (String args []) { int a, b; boolean isprime; for

Will (global) static variables be destroyed at program end? [duplicate]

蓝咒 提交于 2019-11-28 11:50:32
Possible Duplicate: Does C++ call destructors for global and class static variables? What is the lifetime of global MyClass myclass; global static MyClass myclass; global const MyClass myclass; global static const MyClass myclass; function local static MyClass myclass; when its initialization actually occured global static constexpr MyClass myclass; in C++11 and especially will they be destroyed on regular program end (i.e. main is left without an error)? Where does the standard states so. I noticed that a private destructor prevents the creation of all those variables. But if I remember

Rust error: borrow occurs after drop a mutable borrow [duplicate]

拟墨画扇 提交于 2019-11-28 11:30:59
问题 This question already has answers here : What are non-lexical lifetimes? (1 answer) Moved variable still borrowing after calling `drop`? (2 answers) What are the options to end a mutable borrow in Rust? (1 answer) Closed 8 months ago . My test code: let mut c = 0; let mut inc = || { c += 1; c }; drop(inc); println!("{}", c); rustc says: error[E0502]: cannot borrow `c` as immutable because it is also borrowed as mutable --> .\src\closure.rs:20:24 | 12 | let mut inc = || { c += 1; c }; | -- ---

Returning iterator of a Vec in a RefCell

流过昼夜 提交于 2019-11-28 11:17:19
Given the following struct and impl : use std::slice::Iter; use std::cell::RefCell; struct Foo { bar: RefCell<Vec<u32>>, } impl Foo { pub fn iter(&self) -> Iter<u32> { self.bar.borrow().iter() } } fn main() {} I get an error message about a lifetime issue: error: borrowed value does not live long enough --> src/main.rs:9:9 | 9 | self.bar.borrow().iter() | ^^^^^^^^^^^^^^^^^ does not live long enough 10 | } | - temporary value only lives until here | note: borrowed value must be valid for the anonymous lifetime #1 defined on the body at 8:36... --> src/main.rs:8:37 | 8 | pub fn iter(&self) ->

Extending borrow lifetimes in rust

南楼画角 提交于 2019-11-28 11:10:28
问题 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) =