In the Rust book and docs, str
is being referred to as a slice (in the book they say a slice into a String
).
So, I would expect str
to behave the same as any other slice: I should be able to for example use blanket implementations from std::slice
.
However, this does not seem to be the case:
While this works as expected (playground):
fn main() {
let vec = vec![1, 2, 3, 4];
let int_slice = &vec[..];
for chunk in int_slice.chunks(2) {
println!("{:?}", chunk);
}
}
This fails to compile: (playground)
fn main() {
let s = "Hello world";
for chunk in s.chunks(3) {
println!("{}", chunk);
}
}
With the following error message:
error[E0599]: no method named `chunks` found for type `&str` in the current scope
--> src/main.rs:3:20
|
3 | for chunk in s.chunks(3) {
| ^^^^^^
Does this mean str
is not a regular slice?
If it's not: What is the characteristic of str
, which make it impossible to be a slice?
On a side-note: If the above is an "int slice", shouldn't str
be described as a "char slice"?
The documentation of str
starts with
The
str
type, also called a 'string slice',
The quotes are important here. A str
is a 'string slice', which is not the same as a simple 'slice'. They share the name because they are very similar, but are not related to each other otherwise.
You can however get a regular slice out of a 'str' using as_bytes
. There is also a mutable version, which is unsafe because you could use it to break an important invariant of &str
over &[u8]
: UTF-8 validity.
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