In C++, we can do this:
std::string ar[2] = {std::string("hello"), std::string("world")};
std::string hello = ar[0];
std::string world = ar[1];
and hello and world end up being new strings. I think this is because =operator is implemented like a clone() in Rust.
In Rust, this would look like this:
let ar = vec![String::from("hello"), String::from("world")]
let hello = ar[0].clone();
let world = ar[1].clone();
which gets pretty repetitive very quickly.
Is it possible to make = clone the object instead which seems like the natural behavior?
Short answer: No. In Rust, the assignment operator has move semantics unless the type implements the Copy trait.
String does not implement the Copy trait, but it does implement the Clone trait (which is why we can use clone()). But why is that?
This is an intentional choice by the language designers. Types that cannot be copied via a simple bitwise copy (String is an example, which contains a buffer allocated on the heap) are not allowed to implement the Copy trait. The language designers wanted it to be obvious to programmers which types can be "cheaply" copied with a bitwise copy vs types that are more expensive to copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With