Hacker News new | past | comments | ask | show | jobs | submit login

> 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.




Turns out I was slightly wrong, see above. It's still true that no ownership is taken, but we are mutating the &str.


Awesome, thank you for the explanation. I'm still trying to really understand Rust ownership and pointers.




The deadline for YC's W25 batch is 8pm PT tonight. Go for it!

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

Search: