5 ms·
Rust newbie here. How do you fix the compile error for the example given? I imagine it has something to do with transferring ownership, but I’m not too sure.
by SeekingMeaning 7y ago
Rust newbie here. How do you fix the compile error for the example given? I imagine it has something to do with transferring ownership, but I’m not too sure.
- afandian 7y agoLots of these things that look like syntax problems are in fact design problems surfaced by the compiler. The `nickname` variable holds onto a reference to the substring of `name`. Subsequently `name` is modified (cleared). This forces you to think about the behaviour. Should the nickname remain constant even if the backing `name` string changes? Probably yes, so you'd take a copy at that point.
- Cyph0n 7y agoThe easiest fix is to clone the String, then build a slice from the copy.
- tspiteri 7y agoThe example won't compile because nickname is just a reference to the first three bytes of name, but then name is cleared, so nickname would be a bad reference. That are two ways to go around this: 1. Print the nickname before clearing the name so that nickname is still valid when you print it (swap lines 4 and 5). 2. Make nickname a copy of the first three bytes of name, rather then a reference to the first three bytes of name. let nickname = String::from(&name[..3]);
- edflsafoiewq 7y agoTranspose the print and clear statements.
- takeda 7y agoThe nickname works like alias that only shows 3 characters of the name. Before using nickname the code frees the name making both name and nickname invalid. The error here is use after free and one strengths of rust is to detect errors like this. In C such code would compile, what's worse, it would work and behave correctly most of the time. If your code was more complex (for example using threads) you would get a bug that the code would work fine most of the time, but once in a while it would display garbage.
- umanwizard 7y agoAre you familiar with C++? That example is roughly equivalent to: #include <string> #include <iostream> #include <string_view> int main() { std::string name { "Vivian" }; auto nickname = std::string_view { name }.substr(0, 3); name.clear(); std::cout << "Hello there, " << nickname << "!\n"; } which will happily compile, but whose behavior is undefined.
- gramakri 7y agoIs the behavior undefined because std::string makes a deep copy of the string? I thought 'Vivian' would be placed in read-only memory and as long as you don't modify it, you can hold read-only references to it.
- umanwizard 7y agoYes, `std::string` owns its own copy of the string in typical implementations (as does Rust's `String` type). `std::string_view` references that copy. `std::string::clear` destroys it, leaving the `std::string_view` dangling.
- deleted 7y ago[deleted]