4 ms·
Thanks for providing a real world example of code that looks fine in Rust. If you're not using lifetimes, do you still get all the safety guarantees?
by optymizer 6y ago
Thanks for providing a real world example of code that looks fine in Rust. If you're not using lifetimes, do you still get all the safety guarantees?
- coldpie 6y agoYes, definitely. You only need explicit lifetimes for when it's impossible for the borrow checker to figure out the lifetimes for itself. For example if one struct references another, the borrow checker can't know which struct should outlive the other. The vast majority of the time, the borrow checker can figure it out automatically without your help. It's discussed here[1] but note that it's Chapter 10 of the book, so it's probably not the best place to start reading if you're new to Rust :) [1] https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html https://doc.rust-lang.org/book/ch10-03-lifetime-syntax.html E: There are only three instances of using explicit lifetimes in the entirety of the project I linked, if you want to see some real-world examples of it. In all of these, it is used to indicate that the struct being declared references another struct which must outlive that struct. That way we don't end up with a dangling reference if the referenced struct failed to outlive this struct. https://github.com/ValveSoftware/Proton/blob/proton_5.13/media-converter/src/audioconv.rs#L406 https://github.com/ValveSoftware/Proton/blob/proton_5.13/med... https://github.com/ValveSoftware/Proton/blob/proton_5.13/media-converter/src/videoconv.rs#L133 https://github.com/ValveSoftware/Proton/blob/proton_5.13/med... https://github.com/ValveSoftware/Proton/blob/proton_5.13/media-converter/src/videoconv.rs#L433 https://github.com/ValveSoftware/Proton/blob/proton_5.13/med...
- lalaithion 6y agoYou're always using lifetimes, but you rarely have to write them out. Writing out lifetimes is only needed when you have a particularly complicated function or data structure; usually the compiler can just compute what the right lifetime should be from the control flow and type of the function.