Understanding Rust Error E0328
Rust Error E0328: Unsize Trait Misuse
Rust Error E0328 occurs when the Unsize trait is implemented directly on a type. The Unsize trait should not be manually implemented, as the compiler automatically provides all implementations for it.
Erroneous code example:
#![allow(unused)]
#![feature(unsize)]
fn main() {
use std::marker::Unsize;
pub struct MyType;
impl<T> Unsize<T> for MyType {}
}
Solution: Using CoerceUnsized
To fix this error, if you are defining your own smart pointer type and want to enable conversion from a sized to an unsized type using the DST coercion system, you should use the CoerceUnsized trait instead of implementing the Unsize trait directly on your type.
Corrected code example:
#![allow(unused)]
#![feature(coerce_unsized)]
fn main() {
use std::ops::CoerceUnsized;
pub struct MyType<T: ?Sized> {
field_with_unsized_type: T,
}
impl<T, U> CoerceUnsized<MyType<U>> for MyType<T>
where T: CoerceUnsized<U> {}
}
Understanding Unsize and CoerceUnsized
The Unsize trait is a marker trait used by the Rust compiler for dynamically sized types (DSTs). It's utilized for coercing pointers and smart pointers from sized to unsized types. Implementing the Unsize trait manually is unnecessary and prone to errors, as the compiler automatically provides its implementations.
On the other hand, the CoerceUnsized trait allows users to define their own smart pointers to enable conversions between dynamically sized and unsized types. By implementing CoerceUnsized, you ensure that your smart pointer can correctly perform conversions and is compliant with Rust's DST coercion system.