Understanding Rust Error E0170
What is Rust Error E0170?
Rust Error E0170 occurs when you try to use the same name for a pattern binding as one of the variants of a type. This can typically happen when working with enums if the variant name is not properly qualified with the enum type.
Erroneous code example
#![deny(warnings)]
enum Method {
GET,
POST,
}
fn is_empty(s: Method) -> bool {
match s {
GET => true,
_ => false
}
}
fn main() {}
In this example, when trying to match the Method enum inside the `is_empty` function, the `GET` variant is not qualified with the enum type - `Method::GET`. Instead, a new variable named `GET` is used in the match clause, which is likely not the desired behavior.
Solution: Properly qualify the variant name
To fix Rust Error E0170, you should qualify the variant name in the match clause by prefixing it with the enum type.
Corrected code example
enum Method {
GET,
POST,
}
fn is_empty(s: Method) -> bool {
match s {
Method::GET => true,
_ => false
}
}
fn main() {}
In this corrected example, the `GET` variant has been properly qualified with the enum type, thus resolving the E0170 error.
Alternative: Import the enum variants into scope
You can also resolve Rust Error E0170 by importing enum variants into the current scope using a wildcard import. This allows you to use the unqualified variant names in the match clause.
Alternative code example
use Method::*;
enum Method { GET, POST }
fn is_empty(s: Method) -> bool {
match s {
GET => true,
_ => false
}
}
fn main() {}
In this alternative example, the enum variants are imported into the current scope using the wildcard import `use Method::*;`, allowing the unqualified variant names to be used in the match clause without causing any errors.