Today I read a great article about how ownership works in rust. Nicely written and illustrated: https://medium.com/@thomascountz/ownership-in-rust-part-1-112036b1126b
Disclaimer: I am neither the author nor a friend of his and this is not a cheap attempt to catch attention for it. The author tweeted about this article and I responded with a question. We got into a little discussion about it and the man/woman behind the rustlang twitter account advised to open a discussion here to clarify it.
The author puts a figure:
and adds the words:
We can see here, that when using a string literal, Rust is copying the value of hello into hello1
and that statement conflicts with my understanding. Maybe it’s just a wording issue. My understanding is that hello and hello1 point to the same piece of data (not sure whether it’s on the stack or the heap in this case) and the operation
let hello1 = hello;
does not produce a copy of the data (his wording “value”) but a copy of the reference to it (I’d call it the memory address).
I’d argue it’s fine having several references to the same piece of data because it is immutable, so it can be shared and it would make no sense to have it twice in memory. At least this holds true for a string literal. As a result, the illustration should be showing both green guys holding on to one “Hello World”-block, not two different ones.
In one answer to the tweet he explains what makes him think there’s really a duplication happening and it might be true for integers, but I’d think it’s a different story for a str which is probably an array of characters behind the scenes and copying that could become quite expensive (especially for large strings).
Please enlighten me (and/or the author) to make sure that, apart from wording issues, we have the right understanding of what’s happening. Also, he might want to correct his article in case there’s something wrong, so others don’t learn it wrong.