[英]Why is `str` encapsulated inside `String` instead of inside a `Box<str>`?
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? 这并没有给我带来任何困难 - 我完全有能力使用
String
- 但是有没有理由将str
封装在自己的特殊类型中而不是更普遍的Box
类型中? If there is a reason then the answer might help me model how to work with Box
differently. 如果是有原因的,那么答案可能会帮助我的模型如何一起工作
Box
不同。
Why is str
encapsulated inside String
instead of inside a Box<str>
? 为什么
str
封装在String
而不是在Box<str>
? Is it simply for convenience of typing such a common structure or is there a deeper reason? 是为了方便输入这样一个共同结构还是有更深层次的原因?
String
is more like a Vec<char>
than a Box<str>
- it has methods to push more char
s on the end, or push a whole str
. String
更像是Vec<char>
不是Box<str>
- 它有方法可以在最后推送更多的char
,或者推送整个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; 像
Box
和Vec
,它拥有它的内容,并把它们放在堆上; unlike Box
, it also extends the functionality of str
beyond its inherent properties. 与
Box
不同,它还将str
的功能扩展到其固有属性之外。
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. str
主要有&self
方法,因为它不能改变它包含的任何字符,因为字符的改变可能意味着长度的改变,并且它不能重新分配自己。 On the other hand String
is like a &mut str
because it provides methods to manipulate str
s. 另一方面,
String
就像一个&mut str
因为它提供了操作str
的方法。
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. 另一方面,
Box<str>
提供任何内容,因为它本质上是一个拥有的str
,所以它只提供我之前谈到的&self
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.