Rust – Where Clause
Last Updated :
15 Sep, 2022
In Rust, we have a concept of bound that is expressed using a where clause. Clauses are applied to arbitrary types as well as to type parameters.
Syntax:
fn function_name<T, U>(v: T) -> U where
T: Foo,
U: Bar
{
// …statements
}
Where clauses are used in scenarios where we declare generic items like impl or struct. Where clause help in distinguishing between generic types and bound.
Understanding where clause using these examples:
Suppose, we have taken an impl that has two traits P & Q parameters. We are expressing the bounds using the where clause in Rust. Here, GFG is the type while GeeksforGeeks is the trait.
impl <P: TraitX + TraitY, Q:
TraitM + TraitN> GeeksforGeeks
<A, D> for GFG {}
// Expressing bounds with a `where` clause
impl <P, Q> GeeksforGeeks<P, Q> for GFG where
P: TraitX + TraitY,
Q: TraitM + TraitN {}
Example:
Rust
use std::fmt::Debug;
trait GFG {
fn geeks_for_geeks( self );
}
impl <T> GFG for T where
Option<T>: Debug {
fn geeks_for_geeks( self ) {
println!( "The parameters of the vector are {:?}" , Some( self ));
}
}
fn main() {
let vec = vec![20, 40, 80];
vec.geeks_for_geeks();
}
|
Output:
Share your thoughts in the comments
Please Login to comment...