Wow, the borrow checker in Rust is a sadist’s dream. I don’t have enough life to spend half of it trying to sweet talk a compiler into happiness. Giving up on the current exercise for now and may return to it once I’ve worked my way through the rest of the book. If anything, this experience is making me appreciate the sweet elegance of Swift even more now. ARC really hits the sweet spot of safety and ergonomics. (I know Rust has other priorities and that’s great but, heck, life’s too short.) :)

Follow

So given that I can’t let things go… went back to the exercise and finished it by overly simplifying it to meet the stated goals:

source.ind.ie/rust-book-exerci

Still, it doesn’t feel right. Why should I have to clone the departments hashmap in the "link" arm of the match statement, for example (apart from keeping the compiler happy).

You can also the see rabbit whole I went into in the linked commit from the readme.

As always, thoughts/comments/improvements welcome :)

@aral You don't have to clone it. Do `for (department_name, employees) in departments.iter()` instead.

@aral
io::stdout().flush().expect("Die in a fire! Love, Rust."); 😂😂

@aral so it is actually really simple. Playground link: play.rust-lang.org/?version=st patch: paste.gnome.org/piqd3mfds

When iterating over a collection you don't want the loop to consume, make sure to *borrow*, not move, it. And I've made the "add" arm a tad nicer using if let & the entry API.

(cc @schlink)

@aral @schlink the reason why your original approach w/ structs failed is because Rust *really* doesn't want you to represent your data as a "web" of objects that all reference each other. That works somewhat well with GC, not quite well but okay-ish with ARC and does not work at all with explicit memory management.

Instead, Rust wants you to get your *ownership* story clear. What owns what? I'd say `Company` keeps a list of its departments and a `Department` keeps a list of its employees.

@aral @schlink you see, learning Rust is not just about memorizing the syntax, you really need to change the way you think about some things. And not just how you think when writing Rust, it kind of opens a new perspective on how you design your code's architecture... and stuff.

It's hard to describe, really... I've already tried to once, back when I used to use Quora, perhaps read that instead of the last paragraph, lol quora.com/Is-Rust-worth-learni

@bugaevc @schlink Neat, thank you; that does look & feel better :) Any special reason (apart from brevity) that you used the vec! macro instead of the factory method on Vec?

@aral @schlink not really, both are fine. I think I find vec![] slightly more idiomatic, but only slightly & I'm not sure others do.

@bugaevc Gotta vent the frustration somewhere amirite? ;P

Sign in to participate in the conversation
Aral’s Mastodon

This is my personal Mastodon.