Explaining Rust Error E0117: Implementing Foreign Traits
Understanding Rust Error E0117
Rust Error E0117 occurs when you try to implement a foreign trait for a foreign type. Foreign traits are traits that are defined in a different crate than the one you are writing. This error ensures compliance with Rust's orphan rules, which were designed to maintain coherence and prevent conflicting trait implementations.
Erroneous Code Example
#![allow(unused)]
fn main() {
impl Drop for u32 {}
}
In this example, the Drop trait is implemented for u32, a foreign type. Since both the trait and the type are foreign, this code violates the orphan rules and triggers E0117.
Fixing Error E0117
To fix Rust Error E0117, ensure that at least one local type is referenced by the trait implementation. Below are two possible ways to resolve the error:
1. Implement the trait for a local type
#![allow(unused)]
fn main() {
pub struct Foo;
impl Drop for Foo {
fn drop(&mut self) { }
}
}
In this example, we defined a local type Foo and implemented the Drop trait for it, thus resolving the error.
2. Use a local type as a type parameter
#![allow(unused)]
fn main() {
pub struct Foo;
impl From<Foo> for i32 {
fn from(i: Foo) -> i32 {
0
}
}
}
Here, we're using the local type Foo as a type parameter in the implementation of the From trait, which makes the implementation compliant with the orphan rules.
Alternatively, you can define a local trait and implement that instead of the foreign trait:
#![allow(unused)]
fn main() {
trait Bar {
fn get(&self) -> usize;
}
impl Bar for u32 {
fn get(&self) -> usize { 0 }
}
}
In this example, we defined a local trait Bar and implemented it for u32.
For more information on the design of the orphan rules, refer to RFC 1023.