error[E0308]: mismatched types. expected `String`, found `&str`
Rust has strict types β you need to convert between them explicitly.
Why this happens
Rust distinguishes between owned types and borrowed references. String is an owned, heap-allocated string, while &str is a borrowed string slice. Unlike languages with implicit coercion, Rust requires explicit conversions. The same applies to numeric types β i32 and f64 are completely different types that wonβt auto-convert.
Fix 1: &str to String
// β Expected String, got &str
let name: String = "Alice";
// β
Convert
let name: String = "Alice".to_string();
// or
let name: String = String::from("Alice");
Fix 2: String to &str
fn greet(name: &str) { println!("Hello, {}", name); }
let name = String::from("Alice");
// β Expected &str, got String
greet(name);
// β
Borrow it
greet(&name);
Fix 3: Number type mismatches
let x: i32 = 42;
let y: f64 = x as f64; // Explicit cast
Alternative solution: Accept both with generics
Use impl AsRef<str> or Into<String> to accept either type:
fn greet(name: impl AsRef<str>) {
println!("Hello, {}", name.as_ref());
}
greet("Alice"); // &str works
greet(String::from("Alice")); // String works too
Prevention
- Prefer
&strin function parameters when you only need to read the string β it accepts both&strand&String. - Use
cargo clippyto catch unnecessary type conversions and suggest idiomatic alternatives.
Related: Rust cheat sheet Β· Rust: Cannot Borrow as Mutable β Borrow Checker Errors Explained Β· Rust: Value Used After Move β How to Fix It