1

Considering the following program:

fn main() {
    let s = String::from("helloworld");
    // This works fine
    println!("The first word is: {}", first_word(&s));
    // This won't compile
    println!("The first word is: {}", first_word(&s[..]));
    // This works fine
    println!("The first word is: {}", first_word1(&s));
    // This works fine
    println!("The first word is: {}", first_word1(&s[..]));
}

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 first_word1(s: &str) -> &str {
    let bytes = s.as_bytes();

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

    &s[..]
}

It seems that for a &str parameter, you can use either a &String or a &str as argument, but for a &String parameter, only &String is allowed. It also seems that if a function returns &str in its signature, it can return either a &String or a &str, the caller of the function won't see any difference.

So my question is, what is the difference between &String and &str, in parameter types and return types of rust function signatures?

Romstar
  • 1,139
  • 3
  • 14
  • 21
  • 2
    See https://stackoverflow.com/a/24159933/2955999 – okket Mar 04 '21 at 03:13
  • 2
    You've kind of already found this out, [in general you should prefer &str over &String as function parameters since the former is more accepting](https://stackoverflow.com/questions/40006219/why-is-it-discouraged-to-accept-a-reference-to-a-string-string-vec-vec-o) – kmdreko Mar 04 '21 at 03:35

0 Answers0