Questions tagged [lifetime]

A variable's life-time is the time during which the variable is bound to a specific memory location. The life time starts when the variable is allocated and ends when it is deallocated.

Most of the time a lifetime is a synonym for the scope, for example in this code:

void foo()
{
    int x = 0; // lifetime of `x' begins here ──┐
    //                                          │
    printf("%d\n", x); //                       │
} // and finishes here ─────────────────────────┘

Rust:

The lifetime is a key concept in : it is a construct the compiler (also called the ) uses to ensure all borrows are valid.

Links:

2138 questions
24
votes
3 answers

How to initialize a variable with a lifetime?

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…
Hinogary
  • 442
  • 1
  • 3
  • 7
24
votes
4 answers

Rust struct can borrow "&'a mut self" twice, so why can't a trait?

The following Rust code compiles successfully: struct StructNothing; impl<'a> StructNothing { fn nothing(&'a mut self) -> () {} fn twice_nothing(&'a mut self) -> () { self.nothing(); self.nothing(); } } However, if we…
emk
  • 60,150
  • 6
  • 45
  • 50
23
votes
1 answer

Use of variable in own initializer

[basic.scope.pdecl]/1 of the C++20 standard draft had the following (non-normative) example in a note (partial quote from before the merge of pull request 3580, see answer to this question): unsigned char x = x; [...] x is initialized with its own…
walnut
  • 21,629
  • 4
  • 23
  • 59
23
votes
2 answers

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

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…
user1282993
23
votes
2 answers

"error: closure may outlive the current function" but it will not outlive it

When I try to compile the following code: fn main() { (...) let mut should_end = false; let mut input = Input::new(ctx); input.add_handler(Box::new(|evt| { match evt { &Event::Quit{..} => { …
MrNosco
  • 339
  • 1
  • 2
  • 6
23
votes
2 answers

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

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.…
RajV
  • 6,860
  • 8
  • 44
  • 62
23
votes
2 answers

Using a `let` binding to increase a values lifetime

I wrote the following code to read an array of integers from stdin: use std::io::{self, BufRead}; fn main() { let stdin = io::stdin(); for line in stdin.lock().lines() { let xs: Vec = line.unwrap() .trim() …
Thomas Ahle
  • 30,774
  • 21
  • 92
  • 114
22
votes
2 answers

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

I know that calling destructor explicitly can lead to undefined behavior because of double destructor calling, like here: #include int main() { std::vector foo(10); foo.~vector(); return 0; // Oops, destructor will be…
yeputons
  • 8,478
  • 34
  • 67
22
votes
1 answer

How can I take ownership of a Vec element and replace it with something else?

I am writing a function of the following format: fn pop(data: &mut Vec>) -> Option { // Let the item be the current element at head let item = data[0]; // and "remove" it. data[0] = None; item } When I try to…
Cameron Sun
  • 423
  • 1
  • 4
  • 9
21
votes
3 answers

How do I make format! return a &str from a conditional expression?

I happened upon this problem where format! creates a temporary value in a pattern that is not anchored to anything, as far as I understand it. let x = 42; let category = match x { 0...9 => "Between 0 and 9", number @ 10 => format!("It's a…
Bjarke Pedersen
  • 213
  • 2
  • 6
20
votes
2 answers

Does a constant reference member variable in an anonymous struct extend the lifetime of a temporary?

Consider the following code: struct Temp{ int i = 0; }; Temp GetTemp() { return Temp{}; } int main() { for (struct{Temp const & t; int counter;} v = {GetTemp(), 0}; v.counter < 10; ++v.counter) { // Is v.t…
Sedenion
  • 5,421
  • 2
  • 14
  • 42
20
votes
1 answer

Mysterious lifetime issue while implementing trait for dyn object

Consider the following toy example: use std::cmp::Ordering; pub trait SimpleOrder { fn key(&self) -> u32; } impl PartialOrd for dyn SimpleOrder { fn partial_cmp(&self, other: &dyn SimpleOrder) -> Option { …
orlp
  • 112,504
  • 36
  • 218
  • 315
20
votes
1 answer

Why is adding a lifetime to a trait with the plus operator (Iterator + 'a) needed?

I'm applying a closure on the iterator and I want to use stable, so I want to return a boxed Iterator. The obvious way to do so is the following: struct Foo; fn into_iterator(myvec: &Vec) -> Box> { …
torkleyy
  • 1,137
  • 9
  • 26
20
votes
2 answers

Is accessing a static out of scope undefined behavior?

While speaking with a colleague of mine, they said that: foo() { int *p; { int x = 5; p = &x; } int y = *p; } creates undefined behavior because lifetime rules and scope rules do not specify. However: foo() { …
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
20
votes
1 answer

Why can't I return an &str value generated from a String?

I'm having some trouble trying to grasp why I can't return an &str value generated from a String (goodness, when will as_str be ready?) and I'm doing something wrong. I get this idea because nothing that I do makes the value live long enough to…
Brandon Buck
  • 7,177
  • 2
  • 30
  • 51