Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

rust - What does it mean for a trait to have a lifetime parameter?

I understand how lifetime parameters apply to functions and structs, but what does it mean for a trait to have a lifetime parameter? Is it a shortcut to introduce a lifetime parameter to its methods, or is it something else?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have a trait with a lifetime bound, then implementors of the trait can participate in the same lifetime. Concretely, this allows you to store references with that lifetime. It is not a shortcut for specifying lifetimes on member methods, and difficulty and confusing error messages lie that way!

trait Keeper<'a> {
    fn save(&mut self, v: &'a u8);
    fn restore(&self) -> &'a u8;
}

struct SimpleKeeper<'a> {
    val: &'a u8,
}

impl<'a> Keeper<'a> for SimpleKeeper<'a> {
    fn save(&mut self, v: &'a u8) {
        self.val = v
    }
    fn restore(&self) -> &'a u8 {
        self.val
    }
}

Note how both the struct and the trait are parameterized on a lifetime, and that lifetime is the same.

What would the non-trait versions of save() and restore() look like for SimpleKeeper<'a>?

Very similar, actually. The important part is that the struct stores the reference itself, so it needs to have a lifetime parameter for the values inside.

struct SimpleKeeper<'a> {
    val: &'a u8,
}

impl<'a> SimpleKeeper<'a> {
    fn save(&mut self, v: &'a u8) {
        self.val = v
    }
    fn restore(&self) -> &'a u8 {
        self.val
    }
}

And would they mean exactly the same thing as the the trait version?

Yep!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...