Understanding Rust Error E0193
Rust Error E0193: Invalid usage of where clause
Rust Error E0193 occurs when a where clause is used incorrectly in a trait implementation. The where clause should only reference generic type parameters, otherwise it does not make sense to include it.
Erroneous example triggering E0193
```rust
#![allow(unused)]
fn main() {
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl Foo for Wrapper<u32> where Wrapper<u32>: Clone {
fn bar(&self) { }
}
}
```
In the above example, the where clause is added to the implementation of the Foo trait for Wrapper<u32>, which is strange, since there's no need to specify that Wrapper<u32> implements Clone. This is because it's already derived as part of Wrapper<T>, and u32 is a concrete type.
Corrected example
```rust
#![allow(unused)]
fn main() {
trait Foo {
fn bar(&self);
}
#[derive(Copy,Clone)]
struct Wrapper<T> {
Wrapped: T
}
impl <T> Foo for Wrapper<T> where Wrapper<T>: Clone {
fn bar(&self) { }
}
}
```
Here, the where clause is used correctly. It specifies that for any generic type T, the Wrapper<T> implements the Foo trait only when Wrapper<T> is Clone. This is important, as some types might not implement Clone, and therefore would not have the bar() method.
Key concepts
1. Where clauses are used to define additional requirements for implementations, but they should only reference generic type parameters. 2. If a concrete type is used, there's no need for a where clause, since the constraints are already known and fixed. 3. Use where clauses when you need to specify conditions that must be met by generic types in your trait implementations for the implementation to be valid.