102 points · by luu · 11y ago · 83 comments
Lifetime elision seems thoroughly broken or extremely limited in functionality, and now when I'm writing (sometimes seemingly trivial) solutions in Rust I'm spending at least as much time and mental energy explicitly annotating lifetimes as I would be if I was just managing malloc and free in C.
As a result the pain vs. benefit curve doesn't bend nearly as far toward Rust as it theoretically should.
It also could be a programming style thing; I've seen newcomers from C++ often trying to program in the C++ style and having lifetime troubles because the C++ style isn't really amenable to Rust's model. (I feel this might be the issue since you mentioned "sometimes seemingly trivial" -- almost every time someone has said something like that about Rust it's a matter of a programming pattern not translating directly)
Also, really, lifetimes don't do away with the effort required in manual memory management, they just confer it to compile time, so at least you can be sure that your code works and will not break in the future. They're not really a new concept, you think about them anyway in C++, just in a different way.
Most of the cases where I run into this problem and end up feeling like I didn't gain much, if anything, from doing a straight C implementation are situations with deeply nested data structures.
I get that the thinking is that the benefit is that once I've made the compiler stop complaining, my memory management model should at least be sound and safe, and that is a win. Though immediately following that I start to have dream-like fantasies where this entire static analysis stage is simply bolted onto C instead of being a whole new language.
Afterall you can do some pretty impressive stuff with nothing but a pile of preprocessor macros (see Objective C).
Your feeling doesn't line up with what has been observed in practice. Empirically, people do not get the memory management right in C. They mess up, again and again and again. In Rust, however, the compiler enforces that you get it right.
> Though immediately following that I start to have dream-like fantasies where this entire static analysis stage is simply bolted onto C instead of being a whole new language.
I don't think it's really possible to bolt Rust's semantics onto C. Too much will break: in particular C code is not written with inherited mutability, which is critical to Rust. You could maybe do something like the proposed lifetime stuff in C++, which still requires lots of annotation, enough to effectively be a whole new language.
Rust has a lot better ergonomics anyway.
> Afterall you can do some pretty impressive stuff with nothing but a pile of preprocessor macros (see Objective C).
Objective-C isn't "a pile of preprocessor macros", and it would be completely impossible to implement the lifetime system using the preprocessor.
I remember thinking when watching the talk that this was a very bad day for Rust as C++ could now do most of what Rust was promising
If you're using Rust for FFI from functional languages (or any language, really) you need to use a fair amount of unsafe code to get the interface correctly. There's not much benefit for simple things (aside from cases like these: https://gist.github.com/steveklabnik/1a3ec0ca676aaddf766e), but for more complex things it works out pretty nicely.
So if these annotations took the same amount of effort as manually managing malloc() and free(), they'd still be strictly better because they're validated at compile time, no?
If you look at the antipattern example in the "Returning Pointers" section of the Rust book [1], you'll see how you are supposed to handle object creation (the box syntax is the same as Box::new) in a Rustic way
[1] https://doc.rust-lang.org/book/box-syntax-and-patterns.html
Basically, shared ownership is pretty central to many C++ patterns, which means they translate poorly into rust.
Do you have examples? Have you filed bugs?
I don't get why this is needed at all and isn't implicit? What are other possible values for a lifetime in a struct?
That said, the reason it wasn't included in the original elision RFC (https://github.com/rust-lang/rfcs/pull/141) is that the design space here is a little bit more subtle than some of the cases that did make it.
In particular, I believe that it's important to know that a particular struct contains a borrowed value somewhere.
So let's say you could leave off the `'c` on the Sheep struct, and I wrote a struct containing `Sheep`:
struct Flock {
sheep: Vec<Sheep>
}
Now, we have visually lost the fact that a borrowed value is stored inside the flock. Since data structures can get very recursive, this rapidly causes useful information about ownership to get lost.What I'd like to see personally is:
struct Sheep<&> {
age: &i32
}
struct Flock<&> {
sheep: Vec<Sheep>
}
What this would mean is that you can always see, by looking at a struct definition, whether it contains borrowed values (anywhere recursively), but without the grotty need to define and wire up lifetime names.I like the fact that this maintains the strong mental notion of ownership (the meaning of the & "operator" in Rust), but, as with normal elision, it eliminates the wiring that a good compiler should be able to do for you.
I can understand why people feel that way, but it's a bit irrational, because if automatic behaviour can't result into incorrect code, more ressource usage or higher work load, why should I care about?
I have pretty much the same feeling about explicit lifetimes in this example.
Again, I understand that people want the whole control, want to see every relevant information, but everything has its costs, and the relevant information in each use case isn't always the same.
let x = foo; // <- copies
let x = move foo; // <- moves
It was worse, or at least, was by the majority of people at the time. See http://smallcultfollowing.com/babysteps/blog/2012/10/01/move... for more of this ancient history.- only allowing storing references that are valid forever
struct Sheep { age: &'static i32 }
- storing multiple references, with the same lifetime struct Sheep<'a> { age: &'a i32, name: &'a str }
or different ones struct Sheep<'a, 'n> { age: &'a i32, name: &'n str }
(This is usually most important for mutable references (&mut), rather than shared ones (&).)- lifetimes that have a non-trivial relationship to other lifetimes/types, e.g. via trait bounds:
struct Sheep<'a, N: SomeTrait<'a>> { age: &'a i32, name: N }
---There could be some elision rule that allows omitting the explicit annotation in some cases, but I think it would be weird: allowing complete elision for the equivalent thing with types (e.g. writing `struct Foo<T> { x: T }` as just `struct Foo { x: T }`) would not be great at all IMO. These types are generic over lifetimes in essentially the same way as types that are generic over types (i.e. they can be instantiated with a lifetime (resp. type) of a downstream user's choosing), and being generic over a lifetime is part of its signature/behaviour.
You could have
struct Example<'a, 'b>{ ref1: &'a i32, ref2: &'b i32}Think of it like generics. What's the difference between:
struct Foo<T> {x: T, y: T}
and struct Bar<T,U> {x: T, y: U}
"How's T different from U"? That's not the right question to ask -- over here Bar lets T be different from U, whereas in Foo both x and y must have the same type.With the example above
struct Example<'a, 'b>{ ref1: &'a i32, ref2: &'b i32}
this means that there are two references of independent lifetimes. It could also be: struct Example<'a>{ ref1: &'a i32, ref2: &'a i32}
which means that the lifetimes must match, or even struct Example<'a, 'b: 'a>{ ref1: &'a i32, ref2: &'b i32}
which means that 'b is a subset of 'a. (This becomes useful if a struct stores a borrow to a thing and then a borrow of something extracted from that thing)While the first case is the most common (and theoretically could be elided), it's still often a tossup and it's clearer when you know that a struct is borrowing things.
Anyhow; Its definitely worth making two points about lifetimes very clear:
1) They don't exist at runtime.
Lifetimes are purely a compile time thing the compiler uses for formal safety.
2) 'a is not a actual lifetime, it is the minimum possible life time valid for that item; ie. a bound, not a concrete value.
&'a means; this arg/trait/ref/whatever must live at least as long as 'a. That's why different objects with different lifetimes can coexist in a struct of 'a, without needing 'a, 'b, 'c etc for each reference in the struct.
- it is the maximum possible lifetime of the x variable itself,
- it is the minimum lifetime of the `T` instance x points to.
These are 100% related of course (x can't point to something that is invalid), but it is worth being careful about which end of a reference/pointer you're talking about when talking about validity.
Rust is a unique language in that it deallocates memory on the heap
without requiring the writer to call free,
while at the same time having no need for a garbage collector.
Someone correct me if I'm wrong but surely this is not unique - don't Objective C and Swift have automatic reference counting which accomplishes much the same thing?* Not having to worry about trivial memory/resource allocations
ARC - Lifetimes:
* Can blow up hilariously with refcount cycles
* Incurs a runtime overhead
Lifetimes - ARC:
* For the subset of allocation patterns it handles, it does so with zero runtime overhead (i.e. invalid programs do not compile, invalid = leaks memory)
* Use extends beyond just memory allocation/deallocation (see the concurrency docs [1] for example) (note that Mozilla wrote Rust to help write Servo [2], their prototype highly-parallel browser engine, so this use case was a target from the getgo)
* Cannot encode all data structures a GC can (hence why reference counting is part of the stdlib [3])
[1]: https://doc.rust-lang.org/book/concurrency.html
Not quite true- invalid use of lifetimes typically means use-after-free rather than a memory leak (and if you include the standard library, then you can leak memory in safe Rust).
I feel this post confuses two different notions of lifetime. And also mixes concrete lifetimes with lifetime parameters.
There's the CS notion of liveness, and then there's the lifetime notation in Rust.
> To know when to deallocate objects
This is handled by the CS notion of liveness. Well, an approximation to it. "Things are live until they are used, or until they can no longer be used".
The deallocation comes from Rust's affine type system.
In fact, Box<T> and other self-deallocating things don't have an associated "lifetime" in the Rust sense of the word, at least not one that dictates their deallocation.
The lifetime syntax is basically a form of generics which lets one put constraints on the allowed liveness of &-pointers and their ilk.
> example_function<'a> names the lifetime defined by this function, called 'a.
This isn't true. There does exist an anonymous inner lifetime for the scope of the function. It's not `'a`
What's happening here is that we're saying, "For any lifetime `'a`, we can have a version of example_function which returns a pointer which can live that long.". This doesn't compile, because the compiler knows that this function can only return pointers which live as long as its scope or less, not "any" lifetime. (Which is impossible to return from anyway).
This becomes clearer when you have a function like `fn foo<'a> (x: &'a [u8]) -> &'a u8 { &x[0] }` (FWIW if you omit the lifetimes Rust will elide them and internally produce the same function). Here, what we're saying is, "For any lifetime 'a, foo can take a slice that lives as long as 'a and return a pointer that lives as long as 'a". This compiles, because the compiler can see that a reference to x will live as long as x itself.
Similarly, with structs:
> Sheep<'c> instead of Sheep > > This is not doing anything concrete. It's just giving a name to the lifetime that Sheep structs can last for.
This is wrong, too. It's giving a _parameter_ to Sheep, saying "Every Sheep has an associated lifetime 'c, which is the lifetime of its inner reference".
In fact, it is possible to define the body of sheep in such a way that Sheep is guaranteed to live _longer_ than `'c` (instead of shorter, as in the example above). This is explained in the Rustonomicon (http://doc.rust-lang.org/stable/nomicon/subtyping.html). But it's an advanced topic, doesn't crop up often in actual Rust programming.
Another way to phrase it is: the return value of the function is guaranteed to be valid for at least as long as the argument (but may borrow from it, and hence mutations of the argument need to be outlawed as long as the return value is held).