Need Help for the code Snippet

#![allow(unused_variables)]
fn main() {
fn first_word(s: &String) -> &str {
    let bytes = s.as_bytes();

    for (i, &item) in bytes.iter().enumerate() {
        if item == b' ' {
            return &s[0..i];
        }
    }

    &s[..]
}
}

In the above code, we are using "s.as_bytes();" method but actually in the function parameter we are getting only reference of the String then how can we able to convert it value as byte and assign it to byte variable. New to Programming sorry if my question is silly.

As bytes just returns a reference into the Vec<u8> that backs a String. I.e. it converts that the &String to &Vec<u8> (because the vec is a field of string) then into a &[u8] (using as_slice or deref)

In case you didn't know about it, you can see the source code of any function in std by clicking on the src button on the right side of the docs for that function

1 Like