Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If str is a "string slice", why don't std::slice blanket implementations work on str?

Tags:

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

like image 869
Jan15 Avatar asked Jun 22 '19 19:06

Jan15


1 Answers

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.

like image 167
mcarton Avatar answered Dec 02 '22 21:12

mcarton