7

This is supplementary/separate from the Twitch Streams (see sidebar for links), intended for discussion here on lemmy.

The idea being, now that both twitch streams have read Chapter 4, we can have a discussion here and those from the twitch streams can have a retrospective or re-cap on the topic.

This will be a regular occurrence for each discrete set of topics coming out of The Book as the twitch streams cover them


Ownership and the borrow checker are obviously a fundamental and unique topic to rust, so it's well worth getting a good grounding in AFAICT.

  1. Anyone up to trying to summarise or explain ownership/borrow-checker in rust?
    • it can be a good exercise to test your understanding and get feedback/clarification from others ... as well as probably a good way to teach others
  2. Any persistent gripes, difficulties or confusions?
  3. Any of the quizzes from The Book stump you?
  4. Any hard learnt lessons? Or tried and true tips?
top 5 comments
sorted by: hot top new old
[-] Jayjader@jlai.lu 2 points 2 years ago

I said this during my stream of 4.2 (I think): reading about the explicit "Flow" permission was a wonderful validation of my own internalized representation of how variables/lifetimes behave with regards to function calls. Things "flow" into functions, and the only things that "flow out" are what is part of the explicit return value. Deriving this base set of assumptions gives you why you can't just return, from a function, a reference/borrow of data created / memory allocated inside the function call: you need to have the referenced data "flow out" as well.

Persistent gripes

So much time is spent talking about double frees, use-after-frees, and pointers in general yet we never stop to acquire or review what they definitively look like in practice. It feels to me like The Book ends up specifically assuming you have some prior knowledge of low-level/assembly and/or experience implementing a compiler(s), despite it claiming to be agnostic as to your prior programming language in its intro:

Who This Book Is For

This book assumes that you’ve written code in another programming language but doesn’t make any assumptions about which one. We’ve tried to make the material broadly accessible to those from a wide variety of programming backgrounds. We don’t spend a lot of time talking about what programming is or how to think about it. If you’re entirely new to programming, you would be better served by reading a book that specifically provides an introduction to programming.

I understand if the rust internals are too complex to serve as support for introducing lifetimes, but I wish we got equivalent C code or maybe were shown the compiled output for examples illustrating each part of the chapter. For example, if we could be shown how function calls result in stack frames being pushed & popped beyond just the (more abstract) diagrams we already have, or see some malloc() and more importantly free() calls. Or, at least, see some example memory addresses used in the diagrams so that we can figure out for ourselves which pointers are invalid when, instead of having the arrows in the diagrams keep track of the addresses for us.

tried and true tips

  • when you're designing an algorithm to solve a given problem, start with doing as many repeated linear passes over your data collections as you need. Copy/clone/recreate separately anytime you would reach for mutating the original data set. Never [have your code] do more than 1 thing at a time. Only once you have a working implementation of your entire algorithm should you then think about reducing the amount of work your code makes the CPU do to arrive at the same result.

^ this really seems to keep ownership problems: to a minimum, and non-existant during exploratory coding / brainstorming phases.

hard learnt lessons

I am not smart enough to expect to be able to write, first try, rust code that does 0 superfluous copies of data. Attempting to do so always results in going in circles fighting the borrow checker for up to an entire day, before I give up and take the approach I mention above [and often enough end up solving the problem in under half an hour].

[-] maegul@lemmy.ml 1 points 2 years ago

Yep. I’m with you on all of that!

The pitching of The Book is definitely off (this my attempt to write a basic intro to the borrow checker, just to see where my own brain was at but also out of a somewhat fanciful interest in what a better version could look like).

I wonder if the lack of C or assembly equivalents is because the internals aren’t stable??

And yea, optimising data copies on the first go seems to be a trap (for me too!)

Do you know if there are any good tools for analysing the hot spots of data copying?

[-] maegul@lemmy.ml 1 points 2 years ago

Related comment in a separate post: https://lemmy.ml/post/16197939

Provides IMO some really helpful perspective on what references are in rust and how they should be seen and used (in short, they are much more restrictive and constraining than The Book would tell you and should be used conservatively for this reason).

[-] maegul@lemmy.ml 1 points 2 years ago

2. Any persistent gripes, difficulties or confusions?

I'm not entirely sure why, but the whole Double-Free issue never quite sunk in from chapter 4. It's first covered, I think here, section 4.3: Fixing an Unsafe Program: Copying vs. Moving Out of a Collection

I think it was because the description of the issue kinda conflated ownership and the presence or absence of the Copy trait, which isn't covered until way after chapter 4. Additionally, it seems that the issue mechanically comes down to whether the value of a variable is actually a pointer to a heap allocation or not (??)

It was also a behaviour/issue that tripped me up in a later quiz, in an ownership recap quiz in chapter 6 where I didn't pick it up correctly.

Here's the first quiz question that touches on it (see Q2 in The Book here, by scrolling down).

Which of the following best describes the undefined behavior that could occur if this program were allowed to execute?

let s = String::from("Hello world");
let s_ref = &s;
let s2 = *s_ref;
println!("{s2}");

For those not clear, the issue, if this code were permitted to execute, is that s2 would be a pointer to the same String that s points too. Which means that when deallocations occur as the scope ends, both s and s2 would be deallocated, as well as their corresponding memory allocations on the heap. The second such deallocation would then be of undefined content.

I find this simple enough, but I feel like the issue can catch me whenever the code or syntax obscures that a pointer would be copied, not some other value, like in the re-cap quiz in chapter 6 that I got wrong and linked above.

[-] maegul@lemmy.ml 0 points 2 years ago* (last edited 2 years ago)

4. Any hard learnt lessons? Or tried and true tips?

A basic lesson or tip from a discussion in this community (link here):

PS: Abso-fucking-lutely just clone and don’t feel bad about it. Cloning is fine if you’re not doing it in a hot loop or something. It’s not a big deal. The only thing you need to consider is whether cloning is correct - i.e. is it okay for the original and the clone to diverge in the future and not be equal any more? Is it okay for there to be two of this value? If yes, then it’s fine.

IE, using copy/clone as an escape hatch for ownership issues is perfectly fine.


Another one that helps put ownership into perspective I think is this section in the Rustonomicon on unsafe rust, and the section that follows:

There are two kinds of reference:

  • Shared reference: &
  • Mutable reference: &mut

Which obey the following rules:

  • A reference cannot outlive its referent
  • A mutable reference cannot be aliased

That's it. That's the whole model references follow.

Of course, we should probably define what aliased means.

error[E0425]: cannot find value `aliased` in this scope
 --> <rust.rs>:2:20
  |
2 |     println!("{}", aliased);
  |                    ^^^^^^^ not found in this scope

error: aborting due to previous error

Unfortunately, Rust hasn't actually defined its aliasing model. 🙀

While we wait for the Rust devs to specify the semantics of their language, let's use the next section to discuss what aliasing is in general, and why it matters.


Basically it highlights that rust's inferential understanding of the lifetimes of variables is a bit coarse (and maybe a work in progress?) ... so when the compiler raises an error about ownership, it's being cautious (as The Book stresses, unsafe code may not have any undefined behaviour).

It helps I think reframe the whole thing as not being exclusively about correctness but just making sure memory bugs don't happen


Last lesson I think I've gained after chapter 4 was that the implementation and details of any particular method or object matter. The quiz in chapter 6 (question 5) I've mentioned is I think a good example of this. What exactly the Copy and Clone trait are all about too ... where I found looking into those made me comfortable with the general problem space I was navigating in working with ownership in rust. Obviously the compiler is the safe guard, but you don't always want to get beaten over with ownership problems.

this post was submitted on 20 May 2024
7 points (100.0% liked)

Learning Rust and Lemmy

460 readers
7 users here now

Welcome

A collaborative space for people to work together on learning Rust, learning about the Lemmy code base, discussing whatever confusions or difficulties we're having in these endeavours, and solving problems, including, hopefully, some contributions back to the Lemmy code base.

Rules TL;DR: Be nice, constructive, and focus on learning and working together on understanding Rust and Lemmy.


Running Projects


Policies and Purposes

  1. This is a place to learn and work together.
  2. Questions and curiosity is welcome and encouraged.
  3. This isn't a technical support community. Those with technical knowledge and experienced aren't obliged to help, though such is very welcome. This is closer to a library of study groups than stackoverflow. Though, forming a repository of useful information would be a good side effect.
  4. This isn't an issue tracker for Lemmy (or Rust) or a place for suggestions. Instead, it's where the nature of an issue, what possible solutions might exist and how they could be or were implemented can be discussed, or, where the means by which a particular suggestion could be implemented is discussed.

See also:

Rules

  1. Lemmy.ml rule 2 applies strongly: "Be respectful, even when disagreeing. Everyone should feel welcome" (see Dessalines's post). This is a constructive space.
  2. Don't demean, intimidate or do anything that isn't constructive and encouraging to anyone trying to learn or understand. People should feel free to ask questions, be curious, and fill their gaps knowledge and understanding.
  3. Posts and comments should be (more or less) within scope (on which see Policies and Purposes above).
  4. See the Lemmy Code of Conduct
  5. Where applicable, rules should be interpreted in light of the Policies and Purposes.

Relevant links and Related Communities


Thumbnail and banner generated by ChatGPT.

founded 2 years ago
MODERATORS