Open In App

Rust – Where Clause

Last Updated : 15 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




// In this example, we see the usage of the
// where clause. std:: debug is used for debugging 
// the output and we use option <T> 
// as the bound for printing.
  
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:

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads