简体   繁体   中英

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? 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?

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 . 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.

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 str s.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM