Error

"expected &str, found String" — How to Fix

Fix the 'expected &str, found String' error by converting the String to a slice with .as_str() or passing a reference with &.

Convert the String to a string slice (&str) using the .as_str() method or add a reference (&) before the variable name.

fn example(input: &str) {
    let my_string = String::from("hello");
    example(my_string.as_str());
}

Alternatively, if you own the String and don't need it afterwards, pass a reference directly:

fn example(input: &str) {
    let my_string = String::from("hello");
    example(&my_string);
}

If you control the function definition and want to accept ownership of the String, change the parameter type to String:

fn example(input: String) {
    // use input
}

The error occurs because &str is a borrowed string slice (a view into a string), while String is an owned, heap-allocated string. Rust does not automatically convert between them to prevent accidental data copying or ownership confusion.