πŸ”§ Error Fixes
Β· 1 min read

Rust: Expected Type X, Found Y β€” How to Fix It


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 &str in function parameters when you only need to read the string β€” it accepts both &str and &String.
  • Use cargo clippy to 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