Why isn't Deref coercion performed on trait method calls?
⚓ Rust 📅 2026-02-05 👤 surdeus 👁️ 8Why doesn't this code compile Rust Playground
struct Foo(usize);
impl From<&str> for Foo {
fn from(value: &str) -> Self {
Self(value.len())
}
}
fn main() {
let a: &str = "asdf";
let b: &String = &String::from("asdf");
let a_len = Foo::from(a);
let b_len = Foo::from(b); // Error
}
with
help: the trait `From<&String>` is not implemented for `Foo`
but trait `From<&str>` is implemented for it
If I understand correctly from the reference on type coercions, a function call is a "coercion site" and the transformation "&T → &U where T: Deref<Target=U>" is a "coercion type". I assume this is special because trait methods don't count as "coercion sites"? Writing let b_len: Foo = b.into() also does not work, even though (I would assume) that counts as a method call expression, where auto-deref is also performed?
I would love to understand this more.
4 posts - 3 participants
🏷️ Rust_feed