lotsoftools

Understanding and Fixing Rust Error E0520

Introduction to Rust Error E0520

Rust Error E0520 occurs when a non-default implementation is already made on a type but is not marked default, so it cannot be specialized further. In this guide, we'll discuss the error in detail, its cause, and how you can fix it.

Causes of Rust Error E0520

The error stems from the specialization mechanism in Rust traits, which allows you to override default functions in implementations. It requires that all parent implementations are marked as default before any specialization can occur. Error E0520 happens when an attempt to specialize an implementation fails because the parent implementation is not marked default.

Erroneous Code Example

#![allow(unused)]
#![feature(specialization)]

fn main() {
trait SpaceLlama {
    fn fly(&self);
}

// applies to all T
impl<T> SpaceLlama for T {
    default fn fly(&self) {}
}

// non-default impl
// applies to all `Clone` T and overrides the previous impl
impl<T: Clone> SpaceLlama for T {
    fn fly(&self) {}
}

// since `i32` is clone, this conflicts with the previous implementation
impl SpaceLlama for i32 {
    default fn fly(&self) {}
    // error: item `fly` is provided by an `impl` that specializes
    //        another, but the item in the parent `impl` is not marked
    //        `default` and so it cannot be specialized.
}
}

Error E0520 Fix

To fix Rust Error E0520, mark all the parent implementations as default. Here's a corrected version of the erroneous code example:

#![allow(unused)]
#![feature(specialization)]

fn main() {
trait SpaceLlama {
    fn fly(&self);
}

// applies to all T
impl<T> SpaceLlama for T {
    default fn fly(&self) {} // Parent implementation
}

// applies to all `Clone` T; overrides the previous impl
impl<T: Clone> SpaceLlama for T {
    default fn fly(&self) {} // Marked as default, fixing the error
}

// applies to i32, overrides the previous two impls
impl SpaceLlama for i32 {
    fn fly(&self) {} // Now, it's okay!
}
}

Conclusion

Rust Error E0520 occurs when an implementation is specialized without marking all parent implementations as default. To fix this error, ensure you mark parent implementations with the default keyword, enabling further specialization without conflicts.