Why doesn't `From<T>` implement `From<&mut T>`?

I'm trying to understand why here:

use core::marker::PhantomData;

struct B<T>{
    _phantom: PhantomData<T>
}

struct BMut<T>{
    _phantom: PhantomData<T>
}

impl<T> From<BMut<T>> for B<T> {
    fn from(_e: BMut<T>) -> Self {
        B{
            _phantom: PhantomData
        }
    }
}


trait A where Self: Sized {
    fn a(b: Option<&mut B<Self>>, b_mut: &mut BMut<Self>);
}

impl A for u64 {
    fn a(b: Option<&mut B<Self>>, b_mut: &mut BMut<Self>) {
        let b = match b{
            Some(b) => b,
            None => b_mut.into()
        };
    }
}

I get

error[E0277]: the trait bound `&mut B<u64>: From<&mut BMut<u64>>` is not satisfied
  --> src/lib.rs:28:27
   |
28 |             None => b_mut.into()
   |                           ^^^^ the trait `From<&mut BMut<u64>>` is not implemented for `&mut B<u64>`
   |
   = help: the following implementations were found:
             <B<T> as From<BMut<T>>>
   = note: required because of the requirements on the impl of `Into<&mut B<u64>>` for `&mut BMut<u64>`

Why isn't From<> automatically implemented for &mut? Only for T?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c95e615c1303371ce1965fca3216e7e4

My understanding is that T, &T and &mut T are distinct types. This auto-implementation of a trait for reference types wouldn't work well for anything that needs to yield a non-reference type (say the Default trait):

trait Foo {
  fn bar() -> Self;
}

I think you need the following , I have no idea of convert &mut BMut<T> to &mut B<T> , so I use unsafe , just for compile.

impl<T> From<&mut BMut<T>> for &mut B<T> {
    fn from(_e : &mut BMut<T>) -> Self {
        unsafe {
            let x : &mut B<T> = transmute_copy(_e);
            x
        }
    }
}

Please try not to use unsafe code if you don’t know what you’re doing.

fn main() {
    u64::a(None, &mut BMut { _phantom: PhantomData })
}
error: Undefined Behavior: memory access failed: alloc1123 has size 0, so pointer to 8 bytes starting at offset 0 is out-of-bounds
    --> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:2079:14
     |
2079 |     unsafe { copy_nonoverlapping(src, dst, count) }
     |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ memory access failed: alloc1123 has size 0, so pointer to 8 bytes starting at offset 0 is out-of-bounds
     |
     = help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
     = help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
             
     = note: inside `std::intrinsics::copy_nonoverlapping::<u8>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/intrinsics.rs:2079:14
     = note: inside `std::ptr::read_unaligned::<&mut B<u64>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:793:9
     = note: inside `std::mem::transmute_copy::<BMut<u64>, &mut B<u64>>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/mem/mod.rs:960:18
note: inside `<&mut B<u64> as std::convert::From<&mut BMut<u64>>>::from` at src/main.rs:37:33
    --> src/main.rs:37:33
     |
37   |             let x : &mut B<T> = transmute_copy(_e);
     |                                 ^^^^^^^^^^^^^^^^^^
     = note: inside `<&mut BMut<u64> as std::convert::Into<&mut B<u64>>>::into` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/convert/mod.rs:542:9
note: inside `<u64 as A>::a` at src/main.rs:29:21
    --> src/main.rs:29:21
     |
29   |             None => b_mut.into()
     |                     ^^^^^^^^^^^^
note: inside `main` at src/main.rs:44:5
    --> src/main.rs:44:5
     |
44   |     u64::a(None, &mut BMut { _phantom: PhantomData })
     |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     = note: inside `<fn() as std::ops::FnOnce<()>>::call_once - shim(fn())` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:227:5
     = note: inside `std::sys_common::backtrace::__rust_begin_short_backtrace::<fn(), ()>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/sys_common/backtrace.rs:123:18
     = note: inside closure at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:145:18
     = note: inside `std::ops::function::impls::<impl std::ops::FnOnce<()> for &dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe>::call_once` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:259:13
     = note: inside `std::panicking::r#try::do_call::<&dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe, i32>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:406:40
     = note: inside `std::panicking::r#try::<i32, &dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:370:19
     = note: inside `std::panic::catch_unwind::<&dyn std::ops::Fn() -> i32 + std::marker::Sync + std::panic::RefUnwindSafe, i32>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panic.rs:133:14
     = note: inside closure at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:128:48
     = note: inside `std::panicking::r#try::do_call::<[closure@std::rt::lang_start_internal::{closure#2}], isize>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:406:40
     = note: inside `std::panicking::r#try::<isize, [closure@std::rt::lang_start_internal::{closure#2}]>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panicking.rs:370:19
     = note: inside `std::panic::catch_unwind::<[closure@std::rt::lang_start_internal::{closure#2}], isize>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/panic.rs:133:14
     = note: inside `std::rt::lang_start_internal` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:128:20
     = note: inside `std::rt::lang_start::<()>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/std/src/rt.rs:144:17

(in the playground, select “Miri” under “TOOLS” to reproduce)

Even without the confusion in using transmute_copy, using transmute on a struct that isn’t repr(C) or repr(transparent) would probably be unsound. Edit: Actually, I’m not quite sure, maybe it is guaranteed that types that can be zero-sized really are zero-sized :thinking:?

4 Likes

but this can bypass miri (just bypass , this does not really make any sense)

impl<T> From<&mut BMut<T>> for &mut B<T> {
    fn from(_e : &mut BMut<T>) -> Self {
        unsafe {
            let x : usize = 1000;
            let x : &mut B<T> = transmute_copy(&x);
            x
        }
    }
}

Assuming that B<T> is guaranteed to be zero-sized by current Rust rules (I’m not 100% certain on that, but it might be the case), converting a non-zero integer literal into a pointer to a zero-sized type is actually allowed, so miri might be right in the code above not producing any UB.

Converting a type behind mutable references isn’t straightforward. You cannot simply use a conversion A -> B to write a conversion &mut A -> &mut B; the reason is how ownership and borrowing works. A -> B assumes an owned A as input and returns owned B. Trying to create &mut A -> &mut B is problematic because you can’t turn the &mut A into an owned A, and also you can’t return &mut B obtained by borrowing the returned B, because there wouldn’t be any owner around anymore.

Really, a &mut A -> &mut B is usually only possible if A contains a B e.g. as a field (in which case it’s straightforward to implement the conversion), or if both types are somehow equivalent, one is a part of the other, the latter is zero-sized, etc, in which case unsafe code would in-deed be able to create the &mut B from the &mut A. In any case, all of this means that it is not possible for Rust itself to automatically provide conversions in the way you expected/proposed/asked for.


In case I’m misunderstanding your question, please tell me. I’m not 100% certain what you’re referring to with the statement “Only for T?” What exactly is automatically implemented for T?

1 Like
impl From<T> for T

means

impl From<&mut T> for &mut T

but does not mean

impl From<&mut T> for T

maybe this is what confused the author.

this is what I was trying to do:

use core::marker::PhantomData;

struct B<T>{
    _phantom: PhantomData<T>
}

struct BMut<T>{
    _phantom: PhantomData<T>
}

impl<T> From<BMut<T>> for B<T> {
    fn from(_e: BMut<T>) -> Self {
        B{
            _phantom: PhantomData
        }
    }
}


trait A where Self: Sized {
    fn a(b: Option<&mut B<Self>>, b_mut: &mut BMut<Self>);
}

impl A for u64 {
    fn a(b: Option<&mut B<Self>>, b_mut: &mut BMut<Self>) {
        let b = match b{
            Some(b) => b,
            None => b_mut.into()
        };
    }
}

any suggestions then? I basically want to support a function that operates on source and destination, but when source=destination, we don't pass the source and just treat the destination as also being the source.

https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c95e615c1303371ce1965fca3216e7e4