7 ms·
It's like reading "A Discipline of Programming", by Dijkstra. That morality play approach was needed back then, because nobody knew how to think about this stuf
by Animats 1y ago
It's like reading "A Discipline of Programming", by Dijkstra. That morality play approach was needed back then, because nobody knew how to think about this stuff.
Most explanations of ownership in Rust are far too wordy. See [1]. The core concepts are mostly there, but hidden under all the examples.
- Each data object in Rust has exactly one owner.
- Ownership can be transferred in ways that preserve the one-owner rule.
- If you need multiple ownership, the real owner has to be a reference-counted cell.
Those cells can be cloned (duplicated.)
- If the owner goes away, so do the things it owns.
- You can borrow access to a data object using a reference.
- There's a big distinction between owning and referencing.
- References can be passed around and stored, but cannot outlive the object.
(That would be a "dangling pointer" error).
- This is strictly enforced at compile time by the borrow checker.
That explains the model. Once that's understood, all the details can be tied back to those rules.
[1] https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html https://doc.rust-lang.org/book/ch04-01-what-is-ownership.htm...
- ameliaquining 1y agoSummarizing a set of concepts in a way that feels correct and complete to someone who understands them, is a much easier task than explaining them to someone who doesn't. If we put this in front of someone who's only worked with call-by-sharing languages, do you think they'll get it right away? I'm skeptical.
- Animats 1y agoRight. If you come to Rust from C++ and can write good C++ code, you see this as "oh, that's how to think about ownership". Because you have to have a mental model of ownership to get C/C++ code to work. But if you come from Javascript or Python or Go, where all this is automated, it's very strange.
- bloppe 1y agoFor me it really clicked when I realized ownership / lifetimes / references are just words used to talk about when things get dropped. Maybe because I have a background in C so I'm used to manual memory management. Rust basically just calls 'free' for you the moment something goes out of scope. All the jargon definitely distracted me from grasping that simple core concept.
- pinoy420 1y ago[dead]
- josephg 1y agoAlmost all of it. Rust also has the “single mutable reference” rule. If you have a mutable reference to a variable, you can be sure nobody else has one at the same time. (And the value itself won’t be mutated). Mechanically, every variable can be in one of 3 modes: 1. Directly editable (x = 5) 2. Have a single mutable reference (let y = &mut x) 3. Have an arbitrary number of immutable references (let y = &x; let z = &x). The compiler can always tell which mode any particular variable is in, so it can prove you aren’t violating this constraint. If you think in terms of C, the “single mutable reference” rule is rust’s way to make sure it can slap noalias on every variable in your program. This is something that would be great to see in rust IDEs. Wherever my cursor is, it’d be nice to color code all variables in scope based on what mode they’re in at that point in time.
- bloppe 1y agoYa, I just think the `mut` thing isn't as much of a challenge to newcomers as the memory management aspect.
- mikepurvis 1y ago"Rust basically just calls 'free' for you the moment something goes out of scope." C++ does that too with RAII. Go ahead and use whatever STL containers you like, emplace objects onto them, and everything will be safely single-owned with you never having to manually new or delete any of it. The difference is that C++'s guarantees in this regard derive from a) a bunch of implementation magic that exists to hide the fact that those supposedly stack-allocated containers are in fact allocating heap objects behind your back, and b) you cooperating with the restrictions given in the API docs, agreeing not to hold pointers to the member objects or do weird things with casting. You can use scoped_ptr/unique_ptr but the whole time you'll be painfully aware of how it's been bolted onto the language later and whenever you want you can call get() on it for the "raw" underlying pointer and use it to shoot yourself in the foot. Rust formalizes this protection and puts it into the compiler so that you're prevented from doing it "wrong".
- math_dandy 1y agoThe list in the above comment isn’t a summary — it’s a precise definition. It can and must be carefully explained with lots of examples, contrasts with other languages, etc., but the precise definition itself must figure prominently, and examples and intuition should relate back to it transparently.
- andrewflnr 1y agoPractically, I think it suggests that learning the borrow checker should start with learning how memory works, rather than any concepts specific to Rust.
- raincole 1y agoAnd, after someone who doesn't know rust reads this neat and nice summary, they would still know nothing about rust. (Except "this language's compiler must have some black magic in it.")
- ajross 1y agoThe second bullet in the second section is overpromising badly. In fact there are many, many, many ways to write verifiably correct code that leaves no dangling pointers yet won't compile with rustc. Frankly most of the complexity you're complaining about stems from attempts to specify exactly what magic the borrow checker can prove correct and which incantations it can't.
- zigzag312 1y agoA great teaching technique I learned from a very good match teacher is that when explaining core concepts, the simplified definitions don't need to be completely right. They are much simpler to grasp and adding exceptions to these is also quite easy compared to trying to understand correct, but complex, definitions at the beginning.
- ajross 1y agoYeah, but the whole purpose here is "flattening the learning curve", and telling people code will work when it won't is doing the opposite. That bullet, at its most charitable, defines the "idealized goal" of the borrow collector. The actual device is much less capable (as it must be, as the goal is formally undecidable!), and "learning rust" requires understanding how.
- AStonesThrow 1y agoIronically, most people understand "learning curves" counterintuitively. If a "learning curve" is a simple X-Y graph with "time" and "knowledge" being on each axis respectively, then what sort of learning curve is preferable: a flatter one or a steep one? Clearly, if you graph large increases of knowledge over shorter periods of time, a steeper learning curve is more preferable. "Flattening the learning curve" makes it worse! But for some reason, people always reverse this meaning, and so the common idiom breaks down for people who try to reason it out.
- zigzag312 1y ago
- psychoslave 1y agoThis explanation doesn't expose anything meaningful to my mind, as it doesn't define ownership and borrowing, both words being apparently rooted in an analogy with financial asset management. I'm not acquainted with Rust, so I don't really know, but I wonder if the wording plays a role in the difficulty of concept acquisition here. Analogies are often double edged tools. Maybe sticking to a more straight memory related vocabulary as an alternative presentation perspective might help?
- Renaud 1y agoI find it strange that you relate borrowing and ownership to financial asset management. From that angle, it indeed doesn’t seem to make sense. I think, but might be completely wrong, that viewing these actions from their usual meaning is more helpful: you own a toy, it’s yours to do as tou please. You borrow a toy, it’s not yours, you can’t do whatever you want with it, so you can’t hold on to it if the owner doesn’t allow it, and you can’t modify it for the same reasons.
- ithkuil 1y agoAnalogies often leak. 1. In real life I can borrow a toy from you and while I have that toy in my hands, the owner can exchange ownership with somebody else, while the object is borrowed by me. I.e. in real life the borrowing is orthogonal to ownership. In rust you can't do that. 2. Borrowing a toy is more akin to how mutable references work in rust. Immutable references allow multiple people to play with the same toy simultaneously, provided they don't change it. Analogies are just analogies
- psychoslave 1y agoWhat do you mean with usual sense? Maybe it's "financial" that put the interpretation out of the track, but financial comes fidus, that is trust, as in trust that outcomes of reality will meet some expectation of a mental representation.¹ "You own a toy" is the first thing a child is teached as wrong assumption by reality if not by careful social education, isn't it? The reality is, "you can play with the toy in some time frame, and sharing with others is the only way we can all benefit of joyful ludic moment, while claims of indefinite exclusive use of the toy despite limited attention span that an individual can spend on it is socially detrimental." Also memory as an abstract object pragmatically operate on very different ground than a toy. If we could duplicate any human hand grabbable object as information carried by memory holding object, then any economy would virtually be a waste of human attention. ¹ edit: actually I was wrong here, I have been in confusion with "fiduciary". Finance instead comes from french "fin"(end), as in "end of debt".
- xiphias2 1y agoI think the most important lesson is this: Ownership is easy, borrowing is easy, what makes the language super hard to learn is that functions must have signatures and uses that together prove that references don't outlive the object. Also: it's better not store referenced object in a type unless it's really really needed as it makes the proof much much more complex.
- echelon 1y ago> Ownership is easy, borrowing is easy 100%. It's the programmer that needs to adapt to this style. It's not hard by any means at all, it just takes some adjustment.
- geodel 1y agoIndeed. Programmers are holding Rust wrong.
- echelon 1y agoProgrammers new to Rust, you mean. It's kind of like career Java programmers using JavaScript or Python for the first time and bringing their way of doing things.
- cmrdporcupine 1y agoIt's more than that. Rust's value & reference passing semantics are completely different from the way most programmer's have trained their entire lives to think about it. When you pass an argument to a function in Rust, or assign a value into a struct or variable, etc. you are moving it (unless it's Copy). That's extremely different from any other programming language people are used to, where things are broadly pass by value pass by reference and you can just do that as much as you want and the compiler doesn't care. It's as if in C++ you were doing std::move for every single argument or assignment. And so as a programmer you have to shift to a mindset where you're thinking about that happening. This is profoundly unintuitive at first but becomes habit over time. Then having that habit, it's actually a nice reasoning skill when you go back to working in other languages.
- codeflo 1y agoThat's not explaining ownership, that motivating it. Which is fine. The thing that's hard to explain and learn is how to read function signatures involving <'a, 'b>(...) -> &'a [&'b str] or whatever. And how to understand and fix the compiler errors in code calling such a function.
- throwaway81523 1y agoIs it a lot different from std::unique_ptr in C++? I thought the Rust Book was too verbose but I liked Comprehensive Rust: https://google.github.io/comprehensive-rust/ https://google.github.io/comprehensive-rust/ I felt like I understood the stuff in the book based on cursory reading, but I haven't tried to actually use it.
- fastasucan 1y ago>Is it a lot different from std::unique_ptr in C++? Is knowing C++ a pre-requisite?
- casey2 1y agoI would say knowing the useless features of c++ is a pre-requisite for learning rust yes. It's yet another c++ replacement designed by a committee of phds. You would think they would be smart enough to realize that a language taking X hours to learn is a language flaw not a user flaw, but modern education focuses on specialization talents rather than general intelligence.
- PhilipRoman 1y agoRight but Rust is supposed to be a systems language. We already have dozens of languages that are easy to learn. The whole reason for having compile time memory management is to satisfy the constraints of a systems language... I don't think it's much harder than learning C or C++ which are the only comparable mainstream languages.
- 1y ago
- BlackFly 1y agoThat really doesn't explain the model because you have completely left out the distinction between exclusive/shared (or mutable/immutable) borrows. Rust made a large number of choices with respect to how it permits such borrows and those do not follow from this brief outline nor from intuition or common sense. For example, the no aliasing rule is motivated not by intuition or common sense but from a desire to optimize functions. The most complicated aspect of the borrows comes about from the elision rules which will silently do the wrong thing and will work fantastically until they don't at which point the compiler error is pointing at a function complaining about a lifetime parameter of a parameter with the trait method implying that the parameter has to live too long but the real problem was a lifetime in the underlying struct or a previous broken lifetime bound. Those elision rules are again not-intuitive and don't fall out of your explanation axiomatically. They were decisions that were made to attempt to simplify the life of programmers.
- fastasucan 1y ago>the real owner has to be a reference-counted cell. And what is that? Its easy to fall in the trap of making explanations that is very good (if you already understand).
- widforss 1y agoThe only way I could understand the borrow-checker was to implement my own version. Then it made sense.
- frankie_t 1y agoMaybe it's my learning limitations, but I find it hard to follow explanations like these. I had similar feelings about encapsulation explanations: it would say I can hide information without going into much detail. Why, from whom? How is it hiding if I can _see it on my screen_. Similarly here, I can't understand for example _who_ is the owner. Is it a stack frame? Why would a stack frame want to move ownership to its callee, when by the nature of LIFO the callee stack will always be destroyed first, so there is no danger in hanging to it until callee returns. Is it for optimization, so that we can get rid of the object sooner? Could owner be something else than a stack frame? Why can mutable reference be only handed out once? If I'm only using a single thread, one function is guaranteed to finish before the other starts, so what is the harm in handing mutable references to both? Just slap my hands when I'm actually using multiple threads. Of course, there are reasons for all of these things and they probably are not even that hard to understand. Somehow, every time I want to get into Rust I start chasing these things and give up a bit later.
- lucozade 1y ago> _who_ is the owner. Is it a stack frame? The owned memory may be on a stack frame or it may be heap memory. It could even be in the memory mapped binary. > Why would a stack frame want to move ownership to its callee Because it wants to hand full responsibility to some other part of the program. Let's say you have allocated some memory on the heap and handed a reference to a callee then the callee returned to you. Did they free the memory? Did they hand the reference to another thread? Did they hand the reference to a library where you have no access to the code? Because the answer to those questions will determine if you are safe to continue using the reference you have. Including, but not limited to, whether you are safe to free the memory. If you hand ownership to the callee, you simply don't care about any of that because you can't use your reference to the object after the callee returns. And the compiler enforces that. Now the callee could, in theory give you back ownership of the same memory but, if it does, you know that it didn't destroy etc that data otherwise it couldn't give it you back. And, again, the compiler is enforcing all that. > Why can mutable reference be only handed out once? Let's say you have 2 references to arrays of some type T and you want to copy from one array to the other. Will it do what you expect? It probably will if they are distinct but what if they overlap? memcpy has this issue and "solves" it by making overlapped copies undefined. With a single mutable reference system, it's not possible to get that scenario because, if there were 2 overlapping references, you couldn't write to either of them. And if you could write to one, then the other has to be a reference (mutable or not) to some other object. There are also optimisation opportunities if you know 2 objects are distinct. That's why C added the restrict keyword. > If I'm only using a single thread If you're just knocking up small scripts or whatever then a lot of this is overkill. But if you're writing libraries, large applications, multi-dev systems etc then you may be single threaded but who's confirming that for every piece of the system at all times? People are generally really rubbish at that sort of long range thinking. That's where these more automated approaches shine. > hide information...Why, from whom? The main reason is that you want to expose a specific contract to the rest of the system. It may be, for example, that you have to maintain invariants eg double entry book-keeping or that the sides of a square are the same length. Alternatively, you may want to specify a high level algorithm eg matrix inversion, but want it to work for lots of varieties of matrix implementation eg sparse, square. In these cases, you want your consumer to be able to use your objects, with a standard interface, without them knowing, or caring, about the detail. In other words you're hiding the implementation detail behind the interface.
- kaycey2022 1y agoI think the Brown University’s modifications to the rust book do an excellent job of explaining the borrow checker.
- amelius 1y agoSeems incomplete. E.g. what happens if a borrower goes away?
- andromeduck 1y agoIt stops being borrowed?! What kind of question is this.
- amelius 1y agoA question about definitions. Some other options would be: - the object is destroyed - the program core dumps - it is a compile time error Assuming the best possible outcome in case of missing information turns out to be a bad strategy in general.
- agumonkey 1y agoI often wanted to find writings about the 60s on how they approached system/application state at assembly level. I know Sutherland Sketchpad thesis has a lot of details about data structures but I never read it (except for 2-3 pages).
- littlestymaar 1y agoI like how you phrase it, but it's missing the mutable XOR shared for references.
- yung_lean 1y agoIn my experience, understanding the rules of the borrow checker is not enough to be able to write rust code in practice. For example, ~6 months into using rust I was stumped trying to move data out of a mutable reference. Trying to do this directly by dereferencing gives compiler errors like "cannot move out of `*the_ref` which is behind a mutable reference". If you know rust, you're probably either yelling "you idiot! you can't move out of mutable references!" or "you idiot! just use std::mem::take!" (the latter of course being the right way to do this) but that's not obvious from the borrow checker rules. My experience learning rust has been like a death by 1000 cuts, where there's so many small, simple problems that you just have to run into in the wild in order to understand. There's no simple set of rules that can prepare you for all of these situations.
- 3vidence 1y agoI still haven't gotten into rust yet, mostly due to time and demand, but, I have been doing a lot of C++ in the past few years. Coming from that background these rules sound fantastic, theres been a lot of work put into c++ the past few years to try and make these things easier to enforce but it's still difficult to do right even with smart pointers.
- int_19h 1y agoThe main problem is that a lot of things that are correct wrt lifetimes will still not compile because the borrow checker can't prove that they are correct. Even for fairly trivial stuff sometimes, like trees with backlinks.
- bombela 1y agoRust has succeeded in making us hesitant reaching out to raw pointers. To the point we sometimes forget that we can opt-in into unsafe raw pointers on demand. Unlike C/C++ being opt-in to maybe somewhat safe.
- bombela 1y agoI usually teach it by translating it to our physical world by way of an object like a book, which I like to think is intuitive. I have a book. I own it. I can read it, and write into the margin. Tear the pages off if I want. I can destroy it when I am done with it. It is mine. I can lend this book in read only to you and many others at the same time. No modifications possible. Nobody can write to it, not even me. But we can all read it. And borrower can lend it recursively in read only to anybody else. Or I can lend this book exclusively to you in read/write. Nobody but you can write on it. Nobody can read it; not even me; while you borrow it. You could shred the pages, but you cannot destroy the book. You can share it exclusively in read/write to anybody else recursively. When they are done, when you are done, it is back in my hands. I can give you this book. In this case it is yours to do as you please and you can destroy it. If you think low level enough, even the shared reference analogy describes what happens in a computer. Nothing is truly parallel when accessing a shared resource. We need to take turns reading the pages. The hardware does this quickly by means of cached copies. And if you don't want people tearing off pages, give then a read only book except for the margins.
- nayuki 1y ago> the shared reference analogy describes what happens in a computer. Nothing is truly parallel when accessing a shared resource. We need to take turns reading the pages. The hardware does this quickly by means of cached copies. This exists, but it's uncommon: https://en.wikipedia.org/wiki/Dual-ported_RAM https://en.wikipedia.org/wiki/Dual-ported_RAM , https://en.wikipedia.org/wiki/Dual-ported_video_RAM https://en.wikipedia.org/wiki/Dual-ported_video_RAM
- geokon 1y agoI don't do Rust, but I feel there must be more to it that's missing in your description b/c what you wrote sounds exactly like a C++ smart pointer? With the exception of the last point (which I can't imagine tacking on in C++) Maybe I'm missing some subtle point?
- steveklabnik 1y agoThey're very similar at this level of abstraction, the final one is the biggest point.