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
417
votes
5 answers

What is the lifetime of a static variable in a C++ function?

If a variable is declared as static in a function's scope it is only initialized once and retains its value between function calls. What exactly is its lifetime? When do its constructor and destructor get called? void foo() { static string…
Motti
  • 110,860
  • 49
  • 189
  • 262
406
votes
4 answers

Why can't I store a value and a reference to that value in the same struct?

I have a value and I want to store that value and a reference to something inside that value in my own type: struct Thing { count: u32, } struct Combined<'a>(Thing, &'a u32); fn make_combined<'a>() -> Combined<'a> { let thing = Thing {…
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
323
votes
0 answers

Managing the lifetimes of garbage-collected objects

I am making a simplistic mark-and-compact garbage collector. Without going too much into details, the API it exposes is like this: /// Describes the internal structure of a managed object. pub struct Tag { ... } /// An unmanaged pointer to a…
isekaijin
  • 19,076
  • 18
  • 85
  • 153
275
votes
11 answers

Why are explicit lifetimes needed in Rust?

I was reading the lifetimes chapter of the Rust book, and I came across this example for a named/explicit lifetime: struct Foo<'a> { x: &'a i32, } fn main() { let x; // -+ x goes into scope …
corazza
  • 31,222
  • 37
  • 115
  • 186
148
votes
1 answer

What are non-lexical lifetimes?

Rust has an RFC related to non-lexical lifetimes which has been approved to be implemented in the language for a long time. Recently, Rust's support of this feature has improved a lot and is considered complete. My question is: what exactly is a…
Stargateur
  • 24,473
  • 8
  • 65
  • 91
124
votes
5 answers

Is there any way to return a reference to a variable created in a function?

I want to write a program that will write a file in 2 steps. It is likely that the file may not exist before the program is run. The filename is fixed. The problem is that OpenOptions.new().write() can fail. In that case, I want to call a custom…
Nex
  • 1,423
  • 2
  • 10
  • 7
118
votes
7 answers

What is the lifetime of the result of std::string::c_str()?

In one of my programs, I have to interface with some legacy code that works with const char*. Lets say I have a structure which looks like: struct Foo { const char* server; const char* name; }; My higher-level application only deals with…
ereOn
  • 53,676
  • 39
  • 161
  • 238
101
votes
9 answers

"Life-time" of a string literal in C

Wouldn't the pointer returned by the following function be inaccessible? char *foo(int rc) { switch (rc) { case 1: return("one"); case 2: return("two"); default: …
user113454
  • 2,273
  • 9
  • 28
  • 35
93
votes
2 answers

How do I implement the Add trait for a reference to a struct?

I made a two element Vector struct and I want to overload the + operator. I made all my functions and methods take references, rather than values, and I want the + operator to work the same way. impl Add for Vector { fn add(&self, other:…
Jeremy Sorensen
  • 1,100
  • 1
  • 7
  • 14
74
votes
1 answer

Lifetimes in Rust

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 =…
Daniel
  • 10,115
  • 3
  • 44
  • 62
69
votes
4 answers

When is it useful to define multiple lifetimes in a struct?

In Rust, when we want a struct to contain references, we typically define their lifetimes as such: struct Foo<'a> { x: &'a i32, y: &'a i32, } But it's also possible to define multiple lifetimes for different references in the same…
Kai
  • 2,482
  • 1
  • 19
  • 21
68
votes
2 answers

The compiler suggests I add a 'static lifetime because the parameter type may not live long enough, but I don't think that's what I want

I'm trying to implement something that looks like this minimal example: trait Bar {} struct Foo { data: Vec>>, } impl Foo { fn add>(&mut self, x: U) { self.data.push(Box::new(x)); } } Since…
Robert Mason
  • 3,949
  • 3
  • 31
  • 44
63
votes
1 answer

How can I pass a reference to a stack variable to a thread?

I'm writing a WebSocket server where a web client connects to play chess against a multithreaded computer AI. The WebSocket server wants to pass a Logger object into the AI code. The Logger object is going to pipe down log lines from the AI to the…
Ned Ruggeri
  • 1,058
  • 2
  • 8
  • 13
58
votes
3 answers

What is the correct way to use lifetimes with a struct in Rust?

I want to write this structure: struct A { b: B, c: C, } struct B { c: &C, } struct C; The B.c should be borrowed from A.c. A -> b: B -> c: &C -- borrow from --+ | c: C <------------------+ This is…
uwu
  • 1,590
  • 1
  • 11
  • 21
55
votes
3 answers

How do I specify lifetime parameters in an associated type?

I have this trait and simple structure: use std::path::{Path, PathBuf}; trait Foo { type Item: AsRef; type Iter: Iterator; fn get(&self) -> Self::Iter; } struct Bar { v: Vec, } I would like to…
mbrt
  • 1,958
  • 1
  • 17
  • 33
1
2 3
99 100