Open In App

Rust – Bounds

Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of Bounds. Bounds are used in situations when we are working with generics and are trying to figure out the nature and type of parameters that are required for stipulating the functionality that the type in Rust implements.

Syntax:

fn gfg <T: GeeksforGeeks>(x: T) {
   println!(” {}”, x);

//more methods defined
}

In the syntax, we geek is a function where we have the trait GeeksforGeeks as a bound for stipulating the functionality of the type implemented. Here, T is required to be bound by GeeksforGeeks, and therefore the trait T would display GeeksforGeeks.

Example 1:

Rust




// Rust code for Concept of Bounds
use std::fmt::Debug;
  
trait CalculationofPerimeter {
    fn area(&self) -> f64;
}
  
impl CalculationofPerimeter for Square {
    fn area(&self) -> f64 { self.length}
}
  
#[derive(Debug)]
struct Square {length: f64}
#[allow(dead_code)]
fn debug_print_func<T: Debug>(x: &T) {
    println!("{:?} ", x);
}
  
fn main() {
    let sqr = Square {length: 4.0};
    debug_print_func(&sqr);
    }
     


Output:

 

Explanation:

In this example, we have imported use std::fmt::Debug so that the traits are included. We have declared a trait CalculationofPerimeter as a trait and have assigned it as f64 (floating 64bit type). Next with the declared trait CalculationofPerimeter, we have used impl with the trait for the Square which has a length. Following the declarations, we have declared a struct square that has a 64-bit length floating length attribute. Now, to implement a generic trait such as T we have to implement Debug for this type to work correctly. For this reason, we have declared the function debug_print_func and have passed the trait accordingly.

In the main function, we have declared a variable sqr that holds the trait Square, which is then passed on to debug_print_func() as a parameter, and the output is attached.


Last Updated : 19 Oct, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads