Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yum, salad. In my experience this happens when you overspecify a lifetime or something. After I got this code working, I messed with the lifetimes a bit -- I added one extra `'a` tying the lifetimes of something else to existing bound references. That propagated like wildfire and finally became unusable (proving that those two references could not/would not have the same lifetime).

In more complex situations, it's generally worth thinking which lifetime should be bound together for the first few functions and structs. After that point just trust the compiler.

It's not too hard to get a mental model of lifetimes, really, and once you have it you can look at lifetime parameters and figure out what they mean and how they work with each other. You're anyway implicitly thinking of them as scopes. I usually just ignore lifetime parameters -- they're something you learn to gloss over whilst reading Rust code, and I only really read them (and try to understand them) when I have lifetime errors. Sometimes the lifetime error is due to something unfixable, in which case the compiler will often lead me through a wild goose chase saladifying the entire codebase, or the lifetime error is fixable, in which case the compiler's suggestions usually work. Sometimes they don't, but in those situations you can still fix it by trying to understand the why of it (like how I did in this post, though in the case of this post the entire "understand the why of it" was an afterthought) because things worked.



I bet there are a few common "patterns" to rust ownership, and equally many pitfalls and rookie mistakes when one fails to pick one of these patterns. It becomes extra hard if you approach Rust from a Java/Python/C# perspective where the slightest bit of allocation/RAII and mostly even thinking of the stack feels completely alien. You have to learn that and Rust.

I'd love to see a kind of rust ownership tutorial in which you are asked to address a simple CS problem where these patterns occur in Rust. For example, many seem to find it hard to write a factory type. The next problem could be a doubly linked list and so on.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: