lotsoftools

Understanding Rust Error E0211

Introduction to Rust Error E0211

Rust Error E0211 occurs when a function or type does not fit the requirements for where it was used. This error is no longer emitted by the compiler, but understanding its root cause and solution is important. In this article, we will explore four different code examples that previously triggered this error and discuss why they are erroneous and how to fix them.

1. Intrinsic with wrong type

In this first example, using an intrinsic function that has a wrong type can result in Error E0211. To fix it, you should check the function definition to make sure it has the correct type. Here is an example of erroneous code:

#![feature(intrinsics)]

extern "rust-intrinsic" {
    #[rustc_safe_intrinsic]
    fn size_of<T>(); // error: intrinsic has wrong type
}

To fix this issue, update the function definition to include the correct return type:

#![feature(intrinsics)]

extern "rust-intrinsic" {
    #[rustc_safe_intrinsic]
    fn size_of<T>() -> usize; // ok!
}

2. Invalid main function signature

This example is specific to the main function in Rust. The main function must always have the definition `fn main();`, as it doesn't take parameters nor return types. A mismatch in the main function signature would have previously resulted in Rust Error E0211:

fn main() -> i32 { 0 }
// error: main function expects type: `fn() {main}`: expected (), found i32

To resolve this issue, modify the main function signature to the correct definition:

fn main() { }

3. Mismatched types in range

When using a match statement, all patterns must have the same type as the value. Mismatched types in range would have previously resulted in a Rust Error E0211:

let x = 1u8;
match x {
    0u8..=3i8 => (),
    // error: mismatched types in range: expected u8, found i8
    _ => ()
}

To fix the issue, ensure that the pattern and value have the same type:

let x = 1u8;
match x {
    0u8..=3u8 => (), // ok!
    _ => ()
}

4. Mismatched self type

For explicit self parameters, only Box<Self>, &Self, Self, or &mut Self are valid. Mismatched self types would have previously caused Rust Error E0211:

use std::rc::Rc;
struct Foo;

impl Foo {
    fn x(self: Rc<Foo>) {}
    // error: mismatched self type: expected `Foo`: expected struct
    //        `Foo`, found struct `alloc::rc::Rc`
}

To fix the issue, use one of the valid explicit self parameters:

struct Foo;

impl Foo {
    fn x(self: Box<Foo>) {} // ok!
}