# Lifetimes are not object lifetime

> A Rust lifetime is a region of code, not a duration. Annotations, the three elision rules, structs holding references and 'static, set against the C# GC.

- Author: Zeeshan Adil (https://www.internalswithzee.com/about)
- Published: 2026-09-06
- Updated: 2026-11-21
- Source: https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-lifetimes-explained

Chapter 6 of 16 of [Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers.md). Part I, Foundations.

Read this after borrowing. Your goal is to explain which input a returned reference may borrow from and whether it can still be used at a call site. Work through `longer` before the elision rules; the variance note is optional on a first pass.

This is the chapter where the mental model has to change most, because the word is misleading.

In C#, an object's lifetime is commonly discussed in terms of reachability and garbage collection. When it is no longer reachable, it can become eligible for collection, but leaving a local's scope does not by itself tell you exactly when that happens or when memory is reclaimed.

In Rust, a reference lifetime describes a **region of the program** for which the reference must be valid. It is a compile-time relationship, not a timer stored in the reference. The owner still has runtime storage and cleanup behavior; the lifetime annotation describes constraints on using the reference.

That last part is worth demonstrating rather than asserting:

```rust
use std::mem::size_of;

struct Borrowed<'a> { s: &'a str }
struct Owned { s: String }

fn main() {
    println!("&str          {} bytes", size_of::<&str>());
    println!("Borrowed<'a>  {} bytes", size_of::<Borrowed>());
    println!("String        {} bytes", size_of::<String>());
    println!("Owned         {} bytes", size_of::<Owned>());
}
```

```text
&str          16 bytes
Borrowed<'a>  16 bytes
String        24 bytes
Owned         24 bytes
```

A `&str` is a pointer and a length, sixteen bytes on a 64-bit target. Adding a lifetime parameter to a struct adds nothing. The lifetime annotation does not add a lifetime field to the reference. Its purpose is to let the compiler check relationships between borrows; it should not be confused with the storage, reference counting, or allocation costs of the values involved.

**Definition: Region**

A region is a set of points in your program where a reference must remain usable. Not a block, not a stack frame, not a span of time. A set of points.

The compiler's job is to find, for each reference, a region that is large enough to cover every use of that reference and small enough to fit inside the region where the referenced data is valid. If no such region exists, you get a borrow error. That is the entire lifetime system in two sentences.

Getting this wrong is what makes lifetime annotations feel like magic. If you read `'a` as "how long this lives", nothing that follows will make sense. If you read it as "which stretch of code this has to survive", all of it does.

## The simple model, and then the real one

Start with a deliberately simplified picture: a lifetime is a pair of curly braces. A value declared inside a block is valid from its declaration to the closing brace, and any reference to it must not escape that block.

That model is good enough for the next few sections, and it is the model the language actually used until [non-lexical lifetimes shipped in Rust 1.31](https://blog.rust-lang.org/2018/12/06/Rust-1.31-and-rust-2018/) alongside the 2018 edition. It is also wrong in a specific direction, which the previous chapter touched on: a borrow can end after its last relevant use instead of at the closing brace, depending on control flow and the surrounding constraints. So the real model is a set of points in the control flow graph, computed by solving constraints, not a lexical scope.

The distinction matters when you start reading errors. When rustc says a value "does not live long enough", it has computed a region for your reference, computed a region for the data, and found the first does not fit inside the second. It then reports the three points that pin the failure down: where the data was declared, where it was dropped, and where the borrow was still being used. If you have read the [NLL RFC](https://rust-lang.github.io/rfcs/2094-nll.html), that is the machinery. Niko Matsakis's [The Borrow Checker Within](https://smallcultfollowing.com/babysteps/blog/2024/06/02/the-borrow-checker-within/) is the best short piece on why the model is shaped this way.

## The signature is a contract, checked at the boundary

One design decision produces every lifetime annotation you will ever write.

The compiler checks a function body against its signature. It checks every call site against the same signature. It never lets one inform the other. Your caller's borrow checking does not read your function body, and your function body's borrow checking does not read your callers.

So this fails:

```rust
fn longer(a: &str, b: &str) -> &str {
    if a.len() > b.len() { a } else { b }
}
```

```text
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:32
  |
1 | fn longer(a: &str, b: &str) -> &str {
  |              ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the
    signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |          ++++     ++          ++          ++
```

The compiler is not confused about your body. It can see the body. It is refusing to publish an answer that the body happens to imply, because the caller only gets the signature, and a signature that silently depended on the body would break every time you refactored the body.

You have lived with exactly this decision in C#, and you probably never noticed. C# ref safety is also computed from declarations, never from bodies. This compiles cleanly:

```csharp
static ref int Longer(ref int a, ref int b)
    => ref (a > b ? ref a : ref b);
```

C# accepts it without annotation because its rule is coarser. A `ref` parameter may be returned by ref unless you mark it `scoped`, so the compiler assumes the result can come from either argument and asks no further questions here. The cost of that coarseness shows up at the call site instead:

```csharp
int outer = 1;
ref int result = ref outer;
{
    int inner = 2;
    result = ref Longer(ref outer, ref inner);
}
Console.WriteLine(result);
```

```text
error CS8374: Cannot ref-assign 'Longer(ref outer, ref inner)' to 'result'
because 'Longer(ref outer, ref inner)' has a narrower escape scope than 'result'.
```

Same idea, same enforcement point, different vocabulary. The [ref safety design](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md) that C# 11 formalized gives every reference one of a small fixed set of escape scopes: the declaration block, the enclosing method, return-only, or the caller's context. Rust does the same job with an open set of named regions that you can also relate to one another.

## Working the annotated function properly

Now the annotated Rust version:

```rust
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() > b.len() { a } else { b }
}
```

Read it as a claim, not an instruction. "There exists some region `'a`. Both arguments stay valid for at least all of `'a`, and the returned reference stays valid for all of `'a` too." You did not make anything live longer. Annotations never change behavior. They describe relationships that already exist, and the [Rust Book puts it plainly](https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html): lifetime annotations do not change how long any of the references live.

The interesting part is what happens per call site, because `'a` is solved fresh each time.

```rust
fn main() {
    let primary = String::from("primary-endpoint");

    // Call site one: both inputs live to the end of main.
    let fallback = String::from("fallback");
    println!("{}", longer(&primary, &fallback));

    // Call site two: one input dies early, but so does the result.
    {
        let temporary = String::from("tmp");
        println!("{}", longer(&primary, &temporary));
    }

    // Call site three: a literal is 'static, so 'a shrinks to primary's region.
    println!("{}", longer(&primary, "a-very-long-static-literal"));
}
```

```text
primary-endpoint
primary-endpoint
a-very-long-static-literal
```

All three calls compile because each returned reference is used while both candidate inputs remain valid. The second call does not extend `temporary` beyond its block; it finishes using the result before the block ends.

Three calls, three different regions substituted for `'a`. At call site two, `'a` becomes something like "the inner block", because `temporary` cannot support anything larger. That is fine, because the result is only used inside that block. At call site three, one argument is a string literal baked into the binary, valid for the whole program, and the other is not, so `'a` shrinks to fit `primary`.

Now break it:

```rust
fn main() {
    let primary = String::from("primary-endpoint");
    let winner;
    {
        let fallback = String::from("fallback");
        winner = longer(&primary, &fallback);
    }
    println!("{}", winner);
}
```

```text
error[E0597]: `fallback` does not live long enough
  --> src/main.rs:10:35
   |
 9 |         let fallback = String::from("fallback");
   |             -------- binding `fallback` declared here
10 |         winner = longer(&primary, &fallback);
   |                                   ^^^^^^^^^ borrowed value does not live long enough
11 |     }
   |     - `fallback` dropped here while still borrowed
12 |     println!("{}", winner);
   |                    ------ borrow later used here
```

Two constraints, unsatisfiable together. The `println!` forces `'a` to include line 12. The signature forces `fallback` to outlive all of `'a`, and `fallback` dies on line 11. No region satisfies both.

For these particular values, a reader can see that `primary` is longer. The caller is still checked against a signature that allows the result to come from either input. Only if the function's behavior really guarantees the first input is returned should you express a first-input-only lifetime; that is a different contract from a function that chooses the longer string.

```rust
fn longer<'a>(a: &'a str, b: &str) -> &'a str {
    a
}
```

Now `b` gets its own independent region and the broken program above compiles. That narrowing is the direct analogue of C#'s `scoped` modifier:

```csharp
// `scoped` says: this reference cannot be returned or stored past the call.
static ref int First(ref int a, scoped ref int b) => ref a;
```

Swap `First` in for `Longer` at the call site above and it compiles and prints `1`. Different syntax, identical purpose: tell the boundary which input the result can come from. The expressiveness gap is that `scoped` is one bit per parameter, while Rust lets you name as many regions as you need and say how they relate.

**Definition: Subtyping and variance, for lifetimes**

Rust has a subtyping relation, and lifetimes are almost the only place it shows up. If a region `'long` contains a region `'short`, then `&'long T` is a subtype of `&'short T`, and can be used anywhere the shorter one is expected. A reference that is valid for more of the program is valid for less of it.

This is why `'a` in the `longer` signature works even when the two arguments have different real regions. Both get coerced down to the shortest region that satisfies everything, and the result carries that shortest region.

It is also why `&'static str` fits everywhere a `&str` is wanted, and why mutable references behave differently: `&'a mut T` is covariant in `'a` but invariant in `T`, which is what stops you from smuggling a short-lived reference into a long-lived slot through a mutable borrow. The [Reference chapter on subtyping and variance](https://doc.rust-lang.org/reference/subtyping.html) has the full table, and you will not need it until you write a generic type that stores references.

## The three elision rules

You will write hundreds of functions before you type an apostrophe, because the compiler applies three rules first. From the [Reference](https://doc.rust-lang.org/reference/lifetime-elision.html):

1. Each elided lifetime in the parameters becomes a distinct lifetime parameter.
2. If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.
3. If the receiver is `&self` or `&mut self`, that reference's lifetime is assigned to all elided output lifetimes.

One example of each, in a program that compiles:

```rust
struct Limits {
    max: usize,
}

// Rule one only: no output reference, so nothing else to decide.
// Expands to: fn record<'a, 'b>(level: &'a str, message: &'b str)
fn record(level: &str, message: &str) {
    println!("[{}] {}", level, message);
}

// Rule two: exactly one input lifetime, so the output gets it.
// Expands to: fn clamp<'a>(name: &'a str, limits: Limits) -> &'a str
fn clamp(name: &str, limits: Limits) -> &str {
    &name[..name.len().min(limits.max)]
}

struct Router {
    prefix: String,
}

impl Router {
    // Rule three: &self wins, so the output is tied to the router.
    // Expands to: fn prefix<'a>(&'a self) -> &'a str
    fn prefix(&self) -> &str {
        &self.prefix
    }
}

fn main() {
    record("INFO", "started");
    println!("{}", clamp("db-primary", Limits { max: 2 }));
    println!("{}", Router { prefix: "/api/v1".into() }.prefix());
}
```

```text
[INFO] started
db
/api/v1
```

Note `clamp`. It has two parameters and one input lifetime, because `Limits` is an owned value and contributes no region. Rule two counts lifetimes, not parameters, which is why it fires more often than people expect.

Elision does not apply when the rules run out. The `longer` function is the standard case: two input lifetimes, no receiver, so after rule one the compiler has `'a` and `'b` and no basis for choosing. The other case has no inputs at all:

```rust
fn make_name() -> &str {
    let name = String::from("db-1");
    &name
}
```

```text
error[E0106]: missing lifetime specifier
 --> src/main.rs:1:19
  |
1 | fn make_name() -> &str {
  |                   ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but there is
    no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless
      you're returning a borrowed value from a `const` or a `static`
  |
1 | fn make_name() -> &'static str {
  |                    +++++++
help: instead, you are more likely to want to return an owned value
  |
1 - fn make_name() -> &str {
1 + fn make_name() -> String {
  |
```

Take the first suggestion literally and you get the real error, one layer down:

```text
error[E0515]: cannot return reference to local variable `name`
 --> src/main.rs:3:5
  |
3 |     &name
  |     ^^^^^ returns a reference to data owned by the current function
```

This is the C++ dangling reference bug, refused at compile time, in a language where you were not thinking about pointers. The C# version of this function cannot be written wrong, because reachability decides and the collector is still holding the string. Rust has no collector to lean on, so it makes the case unrepresentable instead. The second suggestion is the right one, and it is why the compiler now prints it: return the `String` and let ownership move to the caller.

The elision rules are a stability commitment, defined in [RFC 141](https://rust-lang.github.io/rfcs/0141-lifetime-elision.html) and extended since. More may be added, which is a compatible change because adding a rule only turns errors into working code.

They also have edges. The Reference states rule two as "exactly one lifetime used in the parameters", and yet `fn pick<'a>(a: &'a str, b: &'a str) -> &str` is rejected, because two parameter positions carry a lifetime and the rule counts positions rather than distinct names. The diagnostic does at least name the fix: "consider using the `'a` lifetime".

Rust 1.89 added a warn-by-default lint, [`mismatched_lifetime_syntaxes`](https://blog.rust-lang.org/2025/08/07/Rust-1.89.0/). It fires when the inputs and the outputs of a signature signal a lifetime in different ways, for example `fn items(scores: &[u8]) -> std::slice::Iter<u8>`, where the input advertises a borrow with `&` and the output hides the same lifetime inside a type path.

Diagnostic wording shifts between releases, so the exact text your compiler prints may differ from what is quoted here.

## Elision is a default, not inference

This is the part most tutorials skip, and it is the one that will cost you an afternoon.

Elision does not look at your body and work out the right answer. It applies a fixed rule and produces a signature. If that signature is wrong for what you meant, the body fails to typecheck, and the error is confusing until you know what happened.

```rust
struct Router { prefix: String }

impl Router {
    fn strip(&self, path: &str) -> &str {
        path.strip_prefix(self.prefix.as_str()).unwrap_or(path)
    }
}
```

Rule three fires. The output is tied to `&self`. But the value being returned is a slice of `path`, not of `self`:

```text
error: lifetime may not live long enough
 --> src/main.rs:5:9
  |
4 |     fn strip(&self, path: &str) -> &str {
  |              -            - let's call the lifetime of this reference `'1`
  |              |
  |              let's call the lifetime of this reference `'2`
5 |         path.strip_prefix(self.prefix.as_str()).unwrap_or(path)
  |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |         method was supposed to return data with lifetime `'2`
  |         but it is returning data with lifetime `'1`
  |
help: consider introducing a named lifetime parameter and update trait if needed
  |
4 |     fn strip<'a>(&self, path: &'a str) -> &'a str {
  |             ++++               ++          ++
```

Take the suggestion and it compiles, and the caller can now keep the result after the router is gone. Without it, the router becomes an anchor: every string it hands you is pinned to the router's own lifetime for no reason. In a routing table shared across a request pipeline, that is the difference between a design that composes and one where a lifetime parameter creeps into every type that touches the router.

## Structs that hold references

A struct with a reference field has to declare the relationship, because the struct must not outlive what it borrows:

```rust
struct Parser<'a> {
    input: &'a str,
    position: usize,
}
```

Break it and the error is the same shape as before:

```text
error[E0597]: `text` does not live long enough
  --> src/main.rs:10:34
   |
 9 |         let text = String::from("GET /health");
   |             ---- binding `text` declared here
10 |         parser = Parser { input: &text, position: 0 };
   |                                  ^^^^^ borrowed value does not live long enough
11 |     }
   |     - `text` dropped here while still borrowed
12 |     println!("{} at {}", parser.input, parser.position);
   |                          ------------ borrow later used here
```

Here is a complete one you can run. It parses a log buffer into borrowed views, copies nothing, and shows both elision behaviors in one place:

```rust
struct LogLine<'a> {
    level: &'a str,
    target: &'a str,
    message: &'a str,
}

impl<'a> LogLine<'a> {
    fn parse(line: &'a str) -> Option<LogLine<'a>> {
        let mut parts = line.splitn(3, ' ');
        let level = parts.next()?;
        let target = parts.next()?.trim_end_matches(':');
        let message = parts.next()?;
        Some(LogLine { level, target, message })
    }

    // Tied to the buffer, not to self.
    fn message(&self) -> &'a str {
        self.message
    }

    // Elided: rule three ties this to &self.
    fn target(&self) -> &str {
        self.target
    }
}

fn main() {
    let buffer = String::from(
        "INFO http: request completed\n\
         ERROR db: connection reset by peer\n\
         WARN cache: eviction storm",
    );

    let mut worst: Option<&str> = None;

    for line in buffer.lines() {
        let entry = match LogLine::parse(line) {
            Some(e) => e,
            None => continue,
        };
        println!("{:>5} {:<6} {}", entry.level, entry.target(), entry.message);
        if entry.level == "ERROR" {
            worst = Some(entry.message());
        }
    }

    println!("worst: {:?}", worst);
    println!("buffer bytes: {}", buffer.len());
}
```

```text
 INFO http   request completed
ERROR db     connection reset by peer
 WARN cache  eviction storm
worst: Some("connection reset by peer")
buffer bytes: 90
```

The input contains 90 bytes, and each parsed `&str` points into that buffer instead of allocating a separate string. Constructing the original `String` copies the input into owned storage; the parsing step borrows slices and does not reference-count them.

Now drop the `'a` from `message`'s return type, so it reads `fn message(&self) -> &str`. The program stops compiling:

```text
error[E0597]: `entry` does not live long enough
  --> src/main.rs:43:26
   |
37 |         let entry = match LogLine::parse(line) {
   |             ----- binding `entry` declared here
...
43 |             worst = Some(entry.message());
   |                          ^^^^^ borrowed value does not live long enough
44 |         }
45 |     }
   |     - `entry` dropped here while still borrowed
46 |
47 |     println!("worst: {:?}", worst);
   |                             ----- borrow later used here
```

The data is still perfectly alive. `buffer` outlives everything. What died is the `LogLine` itself, 48 bytes of pointer and length pairs that the compiler was told the result depended on. Elision picked `&self`, and `&self` is the loop variable.

That distinction, `-> &str` versus `-> &'a str` on a borrowed struct's accessor, is the single most useful thing in this chapter if you ever write a zero-copy parser.

## The same shape in C#

You have written this before, with different words:

```csharp
using System;

ref struct LogLine
{
    public ReadOnlySpan<char> Level;
    public ReadOnlySpan<char> Target;
    public ReadOnlySpan<char> Message;

    public static bool TryParse(ReadOnlySpan<char> line, out LogLine result)
    {
        result = default;
        int a = line.IndexOf(' ');
        if (a < 0) return false;
        int b = line.Slice(a + 1).IndexOf(' ');
        if (b < 0) return false;

        result.Level = line.Slice(0, a);
        result.Target = line.Slice(a + 1, b).TrimEnd(':');
        result.Message = line.Slice(a + 1 + b + 1);
        return true;
    }
}

class Program
{
    static void Main()
    {
        string buffer =
            "INFO http: request completed\n" +
            "ERROR db: connection reset by peer\n" +
            "WARN cache: eviction storm";

        foreach (var range in buffer.AsSpan().Split('\n'))
        {
            var line = buffer.AsSpan()[range];
            if (!LogLine.TryParse(line, out var entry)) continue;
            Console.WriteLine($"{entry.Level,5} {entry.Target,-6} {entry.Message}");
        }
    }
}
```

The three log lines come out identical to the Rust version's. The `Split` overload that yields ranges over a span needs .NET 9. The [`ref struct`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct) itself is much older, C# 7.2, though a genuine `ref` field rather than a span-typed one only became legal in C# 11, which is why `Span` had to be special-cased by the runtime before that.

The interesting difference is what you cannot do next. In Rust, collecting borrowed slices into a `Vec` is ordinary code:

```rust
fn errors_in<'a>(buffer: &'a str) -> Vec<&'a str> {
    buffer.lines().filter(|l| l.starts_with("ERROR")).collect()
}
```

The direct `ReadOnlySpan<char>` equivalent cannot be stored in an ordinary class field or `List`. C# can instead store heap-safe `ReadOnlyMemory<char>` views or ranges into an owned string; those make different ownership and access tradeoffs. Trying the span version gives errors:

```csharp
class Errors { public ReadOnlySpan<char> First; }
var errors = new List<ReadOnlySpan<char>>();
```

```text
error CS8345: Field or auto-implemented property cannot be of type
'ReadOnlySpan<char>' unless it is an instance member of a ref struct.

error CS9244: The type 'ReadOnlySpan<char>' may not be a ref struct or a type
parameter allowing ref structs in order to use it as parameter 'T' in the
generic type or method 'List<T>'
```

C# handles this by restricting where the type may appear: not a class field, not a generic argument unless the parameter declares `allows ref struct` (C# 13), not captured, not across an `await`. The rules are per-type and coarse. Rust handles it by tracking, per value, which region it must fit inside, so a `Vec` of references is fine as long as the `Vec` itself does not outlive the buffer.

That is a real expressiveness gap, and it favors Rust. It is also a real complexity gap, and it favors C#. Microsoft's [span usage guidelines](https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines) are a page of rules a person follows. Rust's are a solver you argue with.

## Where borrowed structs scale, and where they stop

The pattern scales in one specific way and fails in another, and knowing which is which is most of the skill.

It scales when there is a natural owner with a clear boundary. Read a request into one buffer, parse headers into slices of it, route on those slices, respond, drop the buffer. Read a log batch, parse ten thousand lines into borrowed views, aggregate, drop. Deserialize a JSON document with borrowed string fields instead of owned ones. In all three the lifetime parameter stays inside one module, because the buffer's region is obvious and everything downstream is shorter.

It fails the moment a borrowed value has to outlive the buffer. Push a `LogLine` onto a queue for a background worker, and the queue must not hold references into a buffer the request thread is about to drop. Cache a parsed value across requests, same problem. Sending it to a background thread that may outlive the buffer has the same constraint. You can transfer or share ownership, copy the needed text, or use a reference-counted buffer; a scoped thread can also borrow when it is guaranteed to finish before the borrowed data goes away.

The failure mode people actually hit is not a crash. It is propagation. A lifetime parameter is viral. Once `Parser<'a>` exists, anything holding a `Parser` needs `'a`, and anything holding that needs `'a`, and three modules later you are threading a region through code that does not care about it. That churn is the real cost, and it is why the advice for month one is to own your data by default, take the allocation, and introduce borrowed types only where a profiler says the copies matter.

There is also a wall you will hit early. A struct cannot own a buffer and borrow from it:

```rust
struct Document<'a> {
    text: String,
    title: &'a str,   // wants to point into self.text
}
```

```text
error[E0505]: cannot move out of `text` because it is borrowed
 --> src/main.rs:9:26
  |
7 |     let text = String::from("Postmortem\nthe cache fell over");
  |         ---- binding `text` declared here
8 |     let title = text.lines().next().unwrap();
  |                 ---- borrow of `text` occurs here
9 |     let doc = Document { text, title };
  |                          ^^^^  ----- borrow later used here
  |                          |
  |                          move out of `text` occurs here
```

Constructing a type that owns a value and stores an ordinary reference into that same value is not supported by this straightforward pattern. Moving a `String` normally moves its handle rather than relocating its heap buffer, but that does not establish a safe self-referential lifetime: the owner could later be moved, mutated, or dropped while the reference is in use. A simple alternative is to store byte ranges and create a slice when needed:

```rust
use std::ops::Range;

struct Document {
    text: String,
    title: Range<usize>,   // an index, not a pointer
}

impl Document {
    fn new(text: String) -> Self {
        let end = text.find('\n').unwrap_or(text.len());
        Document { text, title: 0..end }
    }

    fn title(&self) -> &str {
        &self.text[self.title.clone()]
    }
}
```

A C# object can similarly hold a `string` and offsets into it; the reference keeps the string reachable. In either language the offsets need validation, and Rust string slices also require UTF-8 character boundaries. Recognizing that you have wandered into the self-referential case, and reaching for indices immediately instead of spending two hours on annotations, is worth more than any amount of lifetime theory.

## The two meanings of 'static

Same token, two unrelated jobs.

**As a reference lifetime,** `&'static str` means the data is valid for the entire program. String literals qualify, because they are baked into the binary. So do references to items declared `static`. This is the meaning the compiler suggests when it cannot find a region, and it is almost always the wrong fix for a returned local.

**As a bound on a generic,** `T: 'static` means the type contains no references with a region shorter than the whole program. That is a statement about the type, not about how long a particular value lives. An owned `String` satisfies it. So does `u32`. So does a `Vec` of owned data. None of them live forever, and none of them need to:

```rust
use std::any::type_name;

fn needs_static<T: 'static>(_value: T) {
    println!("{} satisfies T: 'static", type_name::<T>());
}

fn main() {
    let owned = String::from("not a global, not a literal");
    needs_static(owned);          // owned data: fine
    needs_static(42u32);          // no references at all: fine
    needs_static("a literal");    // &'static str: fine
}
```

```text
alloc::string::String satisfies T: 'static
u32 satisfies T: 'static
&str satisfies T: 'static
```

In this example the `String` is dropped at the end of `needs_static`. It satisfied the bound anyway, because the bound constrains references contained in the type rather than requiring this particular value to live forever. Add a borrow of a local and it breaks, and the diagnostic names the mechanism directly:

```text
error[E0597]: `local` does not live long enough
  --> src/main.rs:14:26
   |
13 |     let local = String::from("stack-bound");
   |         ----- binding `local` declared here
14 |     let borrowed: &str = &local;
   |                          ^^^^^^ borrowed value does not live long enough
15 |     needs_static(borrowed);
   |     ---------------------- argument requires that `local` is borrowed for `'static`
16 | }
   | - `local` dropped here while still borrowed
   |
note: requirement that the value outlives `'static` introduced here
  --> src/main.rs:3:20
   |
 3 | fn needs_static<T: 'static>(_value: T) {
   |                    ^^^^^^^
```

You will meet this bound on [`std::thread::spawn`](https://doc.rust-lang.org/std/thread/fn.spawn.html) and on task spawners in async runtimes, and the reason is mechanical: the spawned work may still be running after the calling frame returns, so it must not hold a reference into that frame. It is not saying "give me a global". It is saying "do not lend me your stack".

```rust
use std::thread;

fn main() {
    let name = String::from("worker-1");
    let handle = thread::spawn(|| {
        println!("hello from {}", name);
    });
    handle.join().unwrap();
}
```

```text
error[E0373]: closure may outlive the current function, but it borrows `name`,
which is owned by the current function
 --> src/main.rs:5:32
  |
5 |     let handle = thread::spawn(|| {
  |                                ^^ may outlive borrowed value `name`
6 |         println!("hello from {}", name);
  |                                   ---- `name` is borrowed here
  |
note: function requires argument type to outlive `'static`
help: to force the closure to take ownership of `name` (and any other
      referenced variables), use the `move` keyword
  |
5 |     let handle = thread::spawn(move || {
  |                                ++++
```

Adding `move` transfers ownership into the closure, the closure now contains an owned `String`, and `T: 'static` is satisfied.

Compare what C# does with the same code. The captured local is hoisted into a compiler-generated display class on the heap and stays reachable as long as the delegate is, so `Task.Run(() => Console.WriteLine(name))` works with no ceremony and no decision to make.

This is a case where C# is straightforwardly better for the common path. Rust makes you choose between borrowing with a scoped thread and moving ownership, and the choice is visible in every closure you write. The benefit is an explicit ownership decision at the boundary. That does not guarantee an allocation-free closure: the captured values and the API that stores or schedules the closure can themselves allocate. Whether that trade is worth it depends entirely on whether you were ever going to look at the allocation.

## The mistakes C# engineers make here

**Reading an annotation as a command.** Writing `'static` to "make it live longer" is the reflex, and it never works, because annotations constrain and never extend. You recognize it when adding a lifetime turns one error into a worse one further down. The fix is to ask what region the data actually has and make the signature honest about it.

**Taking the compiler's first suggestion.** On `fn make_name() -> &str`, the `'static` help is listed first and is almost never right. Modern rustc now prints the owned-return suggestion too, and that is nearly always the fix.

**Assuming elision inferred something.** It applied a rule. When a method returns a slice of an argument rather than of `self`, rule three gives you the wrong contract and the body stops typechecking. Recognize the phrase "method was supposed to return data with lifetime `'2`" and reach straight for a named parameter on the argument.

**Reaching for a borrowed struct too early.** A `String` costs 24 bytes of struct plus one allocation. A lifetime parameter costs zero bytes and propagates through every type that touches it. In month one, the second is far more expensive.

**Trying to build a self-referential type.** Owning a buffer and borrowing from it produces E0505 and cannot be annotated away. Switch to indices the moment you see that error on a constructor.

**Reading `T: 'static` as "must be a global".** It means "contains no short-lived references". If adding `move` to a closure fixes your error, this was the confusion.

## Where the C# approach genuinely wins

Anything with cycles or back-pointers. A parent pointer in a tree, an observer list, a cache whose entries reference each other, a doubly linked list. In C# you write the obvious thing and the collector sorts it out. In Rust you reach for indices into a slab, or `Rc` with `Weak` back-edges, or an arena, and every one of those is more code and more thought for a data structure that was not the interesting part of your problem.

Closures over locals, as above. Long-lived object graphs with no clear single owner, which is most of what a business application is. And the plain fact that for a service where every object is heap-allocated and lives for a request, the entire lifetime apparatus buys you a guarantee you were already getting from the runtime, at the cost of a category of compile error you did not have.

C#'s ref safety rules are also easier to learn, precisely because they are coarse. A short fixed ladder of escape scopes, a handful of restrictions on where a `ref struct` may appear, one `scoped` modifier. You can hold all of it in your head. Rust's model is more expressive and correspondingly larger, and the honest summary is that you pay for the expressiveness whether or not you need it.

## Checking yourself

*Why does `fn longer(a: &str, b: &str) -> &str` fail to compile even though the body clearly returns one of the two arguments?*
Because the compiler checks call sites against the signature alone, never against the body. Elision rule one gives the two parameters distinct regions and no rule picks one for the output, so the signature would be ambiguous to every caller.

*A method returns `&str` and the caller gets "does not live long enough" even though the underlying buffer is still alive. What happened?*
Elision rule three tied the returned reference to `&self`, so the compiler thinks the result depends on the receiver rather than on the buffer. Annotate the struct's lifetime explicitly on the return type.

*Does `T: 'static` mean the value must live for the whole program?*
No. It means the type contains no references with a shorter region. An owned `String` satisfies it and is dropped normally. The bound exists to stop you lending a stack frame to something that may outlive it.

*You are writing a struct that holds a `String` and a slice of that same `String`. What should you do?*
Not that. It is self-referential and produces E0505 regardless of annotations. Store a `Range` of byte indices and expose an accessor that slices on demand, validating bounds and UTF-8 boundaries when the ranges are created.

Previous: [Borrowing, and why the compiler counts your references](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-borrowing-and-the-borrow-checker.md)
Next: [Traits are interfaces that do not own your types](https://www.internalswithzee.com/blog/rust-guide-for-csharp-dotnet-engineers/rust-traits-vs-csharp-interfaces.md)
