Using From<&T> to convert from &mut T

Hey,

I noticed, that when I implement the trait From for a reference of a type, and then use the function from with a mutable reference of a type, the compiler throws an error.

I would expect it to auto cast the mutable reference to an immutable reference, as it normally would do. Why doesn’t it do that?

And, is there a derive specification for automatically implementing the trait From for &mut, if it is implemented for &?

EDIT:
Here is a minimal example demonstrating the compilers behaviour: https://play.rust-lang.org/?gist=2bdfaf96462fd5e875a41c848afa6cb4&version=nightly&mode=debug&edition=2015

Rust does not automatically cast mutable references to immutable ones. Sometimes, the compiler will re-borrow something as immutable, but that’s a different behavior. You could do this yourself with

    let t2 = T::from(&*s_mut_ref);

and it will work.

That said, I’m not sure if there’s a specific reason why this From impl is not written. I have some hunches but I’m not sure.

1 Like

This does the reborrow;

let t2 = <T as From<&S>>::from(s_mut_ref);

Without the type qualifier there is the risk at a later stage the trait could be implemented for mut leading to breaking existing code.

1 Like

Thank you for your answers. Actually the explanation that a later implementation of a more specific trait makes sense.
Also, thank you for the casting syntax!