4 ms·
Thanks for all the responses, I'm learning a lot. This explains to me why iterators and other references to the internals of a data type have to take ownership
by sirclueless 10y ago
Thanks for all the responses, I'm learning a lot. This explains to me why iterators and other references to the internals of a data type have to take ownership of the whole data type, which is something I ran into several times during my (brief) explorations with Rust.
- steveklabnik 10y agoTotally. There's one other interesting subtlety you might find interesting here, and that's self-referenceing structs. So for example, struct Foo { s1: String, s2: &str, } where s2 is always intended to point at s1's backing storage. What's unfortunate here is that Rust will disallow this, as it doesn't understand that s2 is pointing to some data on the heap, with a stable address, not the parts of the String struct in s1 that are part of the struct itself. So what this means is, in plain Rust, this type isn't movable, Rust is concerned about the invalidation. However, you can get around this restriction with some unsafe code to teach Rust about it; this is the premise of the "owning-ref" crate.
- Manishearth 10y ago> have to take ownership of the whole data type, This isn't the case. They only need to borrow it. A borrowed value isn't allowed to move (the borrow itself can be copied around and shared within the scope of the borrow), so that works out. Most Rust iterators only borrow the container or iterator they operate on. It's only explicitly moving iterators like .into_iter() (which extracts elements by-move) that don't.