4

It's not causing me any difficulties — I am perfectly capable of using String — but is there any reason that str is encapsulated in its own special type rather than inside the more general Box type? If there is a reason then the answer might help me model how to work with Box differently.

Why is str encapsulated inside String instead of inside a Box<str>? Is it simply for convenience of typing such a common structure or is there a deeper reason?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lemma Prism
  • 371
  • 1
  • 2
  • 8
  • 1
    Possible duplicate of [What are the differences between Rust's \`String\` and \`str\`?](https://stackoverflow.com/questions/24158114/what-are-the-differences-between-rusts-string-and-str) – Zarenor Aug 08 '19 at 21:58
  • 1
    why vector is a vector and not a `Box` ? – Stargateur Aug 08 '19 at 22:53
  • 1
    Note that `Box` is a perfectly valid and occasionally useful type. It's not a "rather than", but "as well as" – trent Aug 08 '19 at 23:50

2 Answers2

7

String is more like a Vec<char> than a Box<str> - it has methods to push more chars on the end, or push a whole str. It has length and capacity, rather than only length. Like Box and Vec, it owns it's contents, and places them on the heap; unlike Box, it also extends the functionality of str beyond its inherent properties.

Zarenor
  • 1,161
  • 1
  • 11
  • 23
  • Ah, so perhaps I should now ask, why isn't it a `Vec`? But thank you, I hadn't realized that requirement--though it's obvious in retrospect. – Lemma Prism Aug 08 '19 at 22:58
  • 3
    @LemmaPrism I'd quibble about `Vec` and prefer to say `Vec` for reasons, but [`String` **is** literally a `Vec`](https://doc.rust-lang.org/1.36.0/src/alloc/string.rs.html#283-285). The source is open and also linked from the docs; feel free to browse it. – Shepmaster Aug 08 '19 at 23:03
  • @Shepmaster That's a fair point. I think I mean conceptually, `Vec` is closer to the concept, but implementation-wise, `Vec` is literally true (and represents the memory footprint more accurately) – Zarenor Aug 09 '19 at 13:02
  • I've belated realized I said `Vec` instead of `Vec`; silly me. But yes, the source is surprisingly easy to review! And thank you @Zarenor for identifying the question I _should_ have asked. – Lemma Prism Aug 12 '19 at 16:35
5

str mainly has &self methods because it cannot change any of the characters it contains because a change in a character might mean a change in the length, and it cannot reallocate itself. On the other hand String is like a &mut str because it provides methods to manipulate strs.

For example, you can push to it, or replace a section.

On the other hand, a Box<str> provides none of this because it is essentially an owned str and so it only provides the &self methods I talked about earlier.

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