-1

I understand that a &str is a slice reference of type &[u8].

If that is the case then why I am not able to iterate it, like this:

let noodles = "noodles".to_string();
let oodles = &noodles[1..];
for elem in oodles {
      println!("{}", elem)
}

I get error:

`&str` is not an iterator; try calling `.chars()` or `.bytes()`

Same code works fine for other types of slice, like a slice reference &[i32]

let myArr = [1,2,3,4];
let mySlice: &[i32] = &myArr;
for elem in mySlice {
   println!("{}", elem);
}
2
  • 7
    &str is not &[u8], it is &str. It is indeed a byte slice under the hood and you can get a reference to that slice with .as_bytes()—but that's rarely what you actually want, as characters can be multibyte. Commented Apr 11, 2024 at 9:25
  • 6
    Please do not get impressed by a single downvote. A single downvote means one user has found your question to be "not show any research effort; unclear or not useful" (as the tooltip says). That being said, it might be the fact that the compiler has suggested the fix. Commented Apr 11, 2024 at 18:55

1 Answer 1

1

A &str is not a &[u8]. It is the case that a &str is effectively backed by bytes, since Rust stores them as UTF-8, and that a &str can be cheaply converted to &[u8], but they are not the same type. &str is used to implement Unicode text and must always be valid UTF-8, while &[u8] is used to implement things which are some arbitrary collection of bytes (which may or not be valid UTF-8).

In your case, there are two possible ways to implement iteration over a &str: as a sequence of characters with data char (by calling chars) or as a series of bytes with data u8 (by calling bytes). There isn't one obvious right choice here, so Rust doesn't automatically implement either of these and you have to choose.

You can get the underlying byte slice with as_bytes, which will implement iteration. However, if you just want to iterate over the bytes, you might as well just call bytes instead, since it will be clearer to others what you intended.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.