3 ms·
I want to make sure I understand this. The original pointer &str does not own the "Hello world" variable but is a reference to it. The new &mut T pointer take
by Junk_Collector 7y ago
I want to make sure I understand this. The original pointer &str does not own the "Hello world" variable but is a reference to it. The new &mut T pointer takes ownership of the &str reference so the original specified (p,11) would be destroyed/overwritten when changed to (p,5). The &mut T cannot edit the underlying string because it the reference it owns is a nonmutable reference. Even if the underlying string, "Hello world" was a mutable str variable, then &mut T could not access it since it was provided and immutable reference &str as its type.
If we provided a mutable pointer to the &mut T, would the mutable pointer would take ownership of the "Hello world"? If so, would Rust then throw a compiler error because we've created a situation where we can orphan part of "Hello world"?
- steveklabnik 7y ago> The original pointer &str does not own the "Hello world" variable but is a reference to it. Correct. > The new &mut T pointer takes ownership of the &str reference &T/&mut T never take ownership. It is true that &mut T must be exclusive, so it's sort of like "temporary ownership", but the underlying T won't be destroyed when the reference goes out of scope. > so the original specified (p,11) would be destroyed/overwritten when changed to (p,5). The original &str will still live as long as it lives; we're creating a new one, and changing the &mut to point to it, not overwriting the existing one. > The &mut T cannot edit the underlying string because it the reference it owns is a nonmutable reference. Even if the underlying string, "Hello world" was a mutable str variable, then &mut T could not access it since it was provided and immutable reference &str as its type. Correct. > If we provided a mutable pointer to the &mut T, would the mutable pointer would take ownership of the "Hello world"? If so, would Rust then throw a compiler error because we've created a situation where we can orphan part of "Hello world"? No, &mut T never takes ownership. Hope that helps! Happy to answer more questions if you've got them.
- steveklabnik 7y agoTurns out I was slightly wrong, see above. It's still true that no ownership is taken, but we are mutating the &str.
- Junk_Collector 7y agoAwesome, thank you for the explanation. I'm still trying to really understand Rust ownership and pointers.