lotsoftools

Understanding Rust Error E0378

Rust Error E0378 explained

Rust Error E0378 occurs when the DispatchFromDyn trait is implemented on something that is not a pointer or a newtype wrapper around a pointer. The DispatchFromDyn trait can only be implemented for built-in pointer types and structs that are newtype wrappers around them.

Erroneous code example

#![allow(unused)]
#![feature(dispatch_from_dyn)]
fn main() {
use std::ops::DispatchFromDyn;

struct WrapperExtraField<T> {
    ptr: T,
    extra_stuff: i32,
}

impl<T, U> DispatchFromDyn<WrapperExtraField<U>> for WrapperExtraField<T>
where
    T: DispatchFromDyn<U>,
{}
}

To fix Rust Error E0378, ensure that the struct has only one field (except for PhantomData), and that field must itself implement DispatchFromDyn.

Correct code example 1

#![allow(unused)]
#![feature(dispatch_from_dyn, unsize)]
fn main() {
use std::{
    marker::Unsize,
    ops::DispatchFromDyn,
};

struct Ptr<T: ?Sized>(*const T);

impl<T: ?Sized, U: ?Sized> DispatchFromDyn<Ptr<U>> for Ptr<T>
where
    T: Unsize<U>,
{}
}

Correct code example 2

#![allow(unused)]
#![feature(dispatch_from_dyn)]
fn main() {
use std::{
    ops::DispatchFromDyn,
    marker::PhantomData,
};

struct Wrapper<T> {
    ptr: T,
    _phantom: PhantomData<()>,
}

impl<T, U> DispatchFromDyn<Wrapper<U>> for Wrapper<T>
where
    T: DispatchFromDyn<U>,
{}
}