eeeeeta / blog-comments

Comments for the blog at theta.eu.org.
0 stars 0 forks source link

Learn You a Rust III - Lifetimes 101 #4

Open utterances-bot opened 5 years ago

utterances-bot commented 5 years ago

Learn You a Rust III - Lifetimes 101

This is the third part of the Learn You a Rust for Great Good! tutorial explainer series.If you’re coming to the series for the first time, I recommend start...

https://theta.eu.org/2016/04/16/lyar-lifetimes.html

towry commented 5 years ago

Hi, I have one question, why don't rust add lifetime specifier automatically since it requires the borrow ref inside struct must live as long as the struct ...?

eeeeeta commented 5 years ago

@towry An unannotated & borrow in a struct doesn't have to live only as long as the struct: it could be 'static. For example:

pub struct Example {
    name: &'static str
}

Also, adding the lifetime specifier on the struct itself makes it clear that the struct is also generic over that lifetime. (that is, Struct<'a> indicates the struct can be used with any lifetime 'a) It wouldn't make sense for Rust to automatically do that for you, as that'd arguably be quite confusing behaviour.

jejuro commented 4 years ago

Concise and clear. Thank you for the article.

aronhegedus commented 1 year ago

Clear example with good explanation, thank you