lotsoftools

Understanding Rust Error E0573

Introduction to Rust Error E0573

Rust Error E0573 occurs when something other than a type is used where a type is expected. This error can appear in various scenarios, such as using an enum variant as a return type, attempting to implement a trait on a const value, or specifying an enum variant as a function argument instead of the entire enum.

Illustrating E0573 with Examples

Below are some erroneous code examples that trigger Rust Error E0573:

Example 1: Using an Enum Variant as a Return Type

```rust
#![allow(unused)]
fn main() {
    enum Dragon {
        Born,
    }

    fn oblivion() -> Dragon::Born { // error!
        Dragon::Born
    }
}
```

Example 2: Attempting to Implement a Trait on a Const Value

```rust
#![allow(unused)]
fn main() {
    const HOBBIT: u32 = 2;
    impl HOBBIT {} // error!
}
```

Example 3: Specifying an Enum Variant as a Function Argument

```rust
#![allow(unused)]
fn main() {
    enum Wizard {
        Gandalf,
        Saruman,
    }

    trait Isengard {
        fn wizard(_: Wizard::Saruman); // error!
    }
}
```

Solutions to Rust Error E0573

Example 1 Solution: Use the Enum as the Return Type

```rust
#![allow(unused)]
fn main() {
    enum Dragon {
        Born,
    }

    fn oblivion() -> Dragon { // ok!
        Dragon::Born
    }
}
```

Example 2 Solution: Create a Struct and Implement the Trait on the Struct

```rust
#![allow(unused)]
fn main() {
    struct Hobbit(u32); // we create a new type

    const HOBBIT: Hobbit = Hobbit(2);
    impl Hobbit {} // ok!
}
```

Example 3 Solution: Use Pattern Matching with the Enum

```rust
#![allow(unused)]
fn main() {
    enum Wizard {
        Gandalf,
        Saruman,
    }

    trait Isengard {
        fn wizard(w: Wizard) { // ok!
            match w {
                Wizard::Saruman => {
                    // do something
                }
                _ => {} // ignore everything else
            }
        }
    }
}
```