Understanding Rust Error E0322: Explicit Implementation of Built-in Trait
Introduction to Rust Error E0322
Rust Error E0322 occurs when a built-in trait is implemented explicitly. These traits have their implementations provided automatically by the compiler and do not need manual implementation.
Example of Erroneous Code
#![allow(unused)]
fn main() {
struct Foo;
impl Sized for Foo {} // error!
}
In this example, the Sized trait is explicitly implemented for the struct Foo, which causes Rust Error E0322.
Explaining Sized Trait
The Sized trait is a built-in trait provided by the Rust compiler for types with a constant size known at compile-time. The compiler automatically provides an implementation of Sized for any eligible types.
Why You Cannot Explicitly Implement Sized
The Sized trait is special because the Rust compiler uses it internally in many places, such as deciding the memory layout and backing storage of structs or arrays. Explicitly implementing it might cause conflicts or undefined behavior. Thus, the compiler disallows explicit implementation of this trait to maintain safety and stability.
How to Correctly Use Sized
To use the Sized trait, rely on the compiler to automatically implement it for eligible types. The following example demonstrates correct usage of the Sized trait:
#![allow(unused)]
fn main() {
struct Foo;
// No explicit implementation of Sized needed
fn takes_sized<T: Sized>(foo: T) {
println!("This function only accepts types that implement Sized.");
}
takes_sized(Foo);
}
How to Handle Non-Sized Types
If you need to work with types that might not implement Sized, like dynamically-sized types or trait objects, you can use the ?Sized trait bound. It will allow your function to accept both Sized and non-Sized types.
#![allow(unused)]
fn main() {
struct Foo;
trait Bar {}
// This function can accept both Sized and non-Sized types
fn takes_unsized<T>(foo: T)
where
T: ?Sized,
{
println!("This function accepts all types, including non-Sized.");
}
takes_unsized(Foo);
}