2

Usually I can use an &String in any function call that accepts an &str, I believe this is because String implements Deref<Target = str>.

In the following case using From it does not work:

struct Foo;

impl From<&str> for Foo {
    fn from(_: &str) -> Foo {
        unimplemented!()
    }
}

fn main() {
    let s = String::new();
    Foo::from(&s);
}

Playground

Yields:

error[E0277]: the trait bound `Foo: From<&String>` is not satisfied
  --> src/main.rs:11:5
   |
11 |     Foo::from(&s);
   |     ^^^^^^^^^ the trait `From<&String>` is not implemented for `Foo`
   |
   = help: the following implementations were found:
             <Foo as From<&str>>
   = note: required by `from`

Why do I not get the Deref I am used to in this case?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
turbulencetoo
  • 3,447
  • 1
  • 27
  • 50
  • Your question might be answered by the answers of [What is the relation between auto-dereferencing and deref coercion?](https://stackoverflow.com/q/53341819/155423). If not, please **[edit]** your question to explain the differences. Otherwise, we can mark this question as already answered. – Shepmaster Dec 04 '20 at 17:39
  • 2
    ahh TY @Shepmaster that's indeed the post I'm looking for. It also explains why doing a fully qualified ```>::from(&s);``` works. – turbulencetoo Dec 04 '20 at 17:44

0 Answers0