rust-lang / rust-lang/rfcs

Lifetime elision for users of structs or traits with manually-defined lifetimes

Open
#1,532 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

tl;dr: Compiler should not force you to manually state lifetimes of traits and structs which had their own lifetimes stated explicitly, unless they cause new ambiguities.

Longer version:
I'm studying Rust lately and I ran into a little problem. I was writing a stupid game using rust-sfml and I thought it was too much of a waste to keep recreating the same objects over and over again.

The code was something like this:

pub struct RenderingComponent {
    window: RenderWindow,
}

impl RenderingComponent {
    pub fn draw(&mut self) {
        let texture = // get texture from file
        let sprite = // create sprite from texture
        self.window.draw(&sprite);
    }
}

So I've decided to cache everything but as soon as I've tried to cache the Sprite object, I had problems. Sprite has an explicit lifetime declaration because it stores an immutable reference to the texture.

pub struct Sprite<'a> {
    texture: &'a Texture,
}

When I tried to cache it (with something like a Vec<Sprite>), that lifetime declaration got into my code and hit it like a bomb. Now I had to rewrite RenderingComponent as RenderingComponent<'a>, which started a cascading effect all the way up to the main function. In the end I've decided against caching the Sprite instance and went on recreating the instance from scratch on every loop iteration.

It would be nice if the compiler could look at Sprite's manually defined lifetime and just sparred me the pain of rewriting all my code making all lifetimes explicit. (Which is a skill I still have to acquire, btw).

Am I missing something here because of my inexperience with the language or is it a valid claim?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with Rust's lifetime-elision rules and the Sprite, RenderingComponent, and main-function examples in the issue. Determine whether the requested behavior can be specified without introducing ambiguity, and document a concrete language-design decision or proposal as the definition of done.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.