Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add OnceCell to shared-mutability + splitting burrows speaker notes #107

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
12 changes: 7 additions & 5 deletions training-slides/src/shared-mutability.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,25 +281,27 @@ To get *shared ownership* and *mutability* you need two things:
If you only need to modify a field *once*, a `OnceCell` can help you keep the ownership system checks at compile-time
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we link to the std-library docs on OnceCell?


```rust
use std::time::Instant;

fn main() {
let post = Post {
content: String::from("Blah"),
..Post::default()
};
assert!(post.days_on_hn_front_page.get().is_none());
assert!(post.first_viewed_at.get().is_none());
println!("{:?}", post.hn_ranking());
assert!(post.days_on_hn_front_page.get().is_some());
assert!(post.first_viewed_at.get().is_some());
}

#[derive(Debug, Default)]
struct Post {
content: String,
days_on_hn_front_page: std::cell::OnceCell<u64>,
first_viewed_at: std::cell::OnceCell<Instant>,
}

impl Post {
fn hn_ranking(&self) -> u64 {
*self.days_on_hn_front_page.get_or_init(|| {7})
fn hn_ranking(&self) -> Instant {
jonathanpallant marked this conversation as resolved.
Show resolved Hide resolved
*self.first_viewed_at.get_or_init(|| {Instant::now()})
miguelraz marked this conversation as resolved.
Show resolved Hide resolved
}
}
```