Understanding Rust Error E0790
Rust Error E0790 Explanation
Rust Error E0790 occurs when the Rust compiler is unable to choose a specific implementation of a trait to call a method. This ambiguity typically arises when multiple implementations are available for the trait to choose from. In order to resolve this error, it's necessary to provide a clear type annotation that informs the compiler which implementation should be used.
Error E0790 Example
Consider the following erroneous code example:
#![allow(unused)]
fn main() {
trait Generator {
fn create() -> u32;
}
struct Impl;
impl Generator for Impl {
fn create() -> u32 { 1 }
}
struct AnotherImpl;
impl Generator for AnotherImpl {
fn create() -> u32 { 2 }
}
let cont: u32 = Generator::create();
// error, impossible to choose one of Generator trait implementation
// Should it be Impl or AnotherImpl, maybe something else?
}
In this example, we have a trait called 'Generator', with two implementations, 'Impl' and 'AnotherImpl'. When we try to call the 'create()' method on 'Generator', the compiler is unable to decide which implementation to use, raising Error E0790.
Resolving Error E0790
To resolve this error, we need to provide type annotations that inform the compiler about the specific implementation to be used. In the updated code example below, we are using a concrete type to call the 'create()' method:
#![allow(unused)]
fn main() {
trait Generator {
fn create() -> u32;
}
struct AnotherImpl;
impl Generator for AnotherImpl {
fn create() -> u32 { 2 }
}
let gen1 = AnotherImpl::create();
// if there are multiple methods with same name (different traits)
let gen2 = <AnotherImpl as Generator>::create();
}
In this example, we have effectively resolved Error E0790 by explicitly specifying which implementation of the 'Generator' trait should be used. Now, the Rust compiler has enough information to correctly call the 'create()' method without ambiguity.