14

What happens when you clone a &str?

Is the cloned &str pointing to the same place as clonee &str or is it something?

Is this documented anywhere?

NebulaFox
  • 7,813
  • 9
  • 47
  • 65
  • Your question might be answered by the answers of [Do all primitive types implement the Copy trait?](https://stackoverflow.com/q/41413336/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Mar 17 '20 at 20:27
  • Very useful answer. So it falls under the Copy trait rather than the Cloning trait? – NebulaFox Mar 17 '20 at 20:30
  • 1
    Copy is a bitwise copy, Clone is a method to actually clone data in a smart way. You can have Clone without Copy, but not vice versa. Please see [the `Copy` docs page](https://doc.rust-lang.org/std/marker/trait.Copy.html). – Optimistic Peach Mar 17 '20 at 20:36
  • 3
    A rite of passage of Rust is understanding that `&T` is `Copy` and `&mut T` is not... I'll let you think about why ;) – Matthieu M. Mar 17 '20 at 20:59

1 Answers1

18

Cloning a &str is the same as cloning any &T; it just copies the reference.

Clone is implemented for any &T. It literally just returns itself since it is Copy.

This is documented under reference's docs.

Optimistic Peach
  • 3,862
  • 2
  • 18
  • 29