Here why it's returning a reference of a reference?

In the below code, the first_word function is taking a reference of String Type and its returning reference of the that reference? Whats the reason?

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[..]
}

fn main() {
    let mut s = String::from("hello world");

    let word = first_word(&s);


    println!("the first word is: {}", word);
}

Rust can "flatten" references with the DeRef trait, so &&str can be treated as &str.

I couldn't parse what you mean by this. That function returns a reference to a substring of the input string.

1 Like

Thats what i'm confused. That function is taking a one parameter (s) which itself is reference and returning reference of input s (which is already a refrenence)

No, indexing dereferences. container[index] is sugar for *Index::index(&container, index) (if the container directly implements Index) or *Index::index(container, index) (if it's a reference to such a type — ie., it's just the usual method resolution rules.)

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.