3 ms·
To be clear, while this is true in the general case, there are specific moments where it does break down, due to the conservative nature of static analysis. Thi
by steveklabnik 10y ago
To be clear, while this is true in the general case, there are specific moments where it does break down, due to the conservative nature of static analysis. This thread has some good examples, but in the interest of transparency, I'll provide another:
struct Foo {
s1: String, // some sort of String data
s2: &str, // a slice of said String
}
What Rust doesn't understand here is that the String's data is on the heap, and therefore, its address is stable. So if you try to construct this, Rust won't let you, because it thinks that the borrow of s1 by s2 would be invalidated by the move. This is fixed by https://crates.io/crates/owning-ref https://crates.io/crates/owning-ref, but it'd be nice if it understood it by default.
In general, these cases are small, but they can be annoying when you run into them. As I said downthread, I very rarely run into them personally, but some others seem to constantly. YMMV.
- rrobukef 10y agoIs this actually safe? What happens if you have ownership, then you can mutate the struct Foo like this: foo.s1 = "World" Which destroys the original heap data. Then s2 is a dangling reference. Since references cannot implement a drop method, you need a wrapping datastructure WITH reference counting, like you said.
- steveklabnik 10y ago> then you can mutate the struct Foo like this: You couldn't because it'd be immutably borrowed.