Rust – Multiple Bounds
Last Updated :
18 Oct, 2022
In Rust, we have a concept of multiple bounds. Multiple bounds are defined under the Traits of Rust programming. Multiple bounds in Rust can be applied with a ‘+’ operator and the types are separated using comma (,)
For needing more than one bounds in Rust programs, we need to import use::std::fmt::Debug or use::std::fmt::{Debug,Display}
Syntax:
use std::fmt::Debug;
fn multiple_bounds_demo<GFG: Clone + Debug>(a: GFG)
{ //methods inside the function trait }
Example 1:
Rust
# Printing Two trait values using multiple bounds
#![allow(unused_variables)]
use std::fmt::{Debug, Display};
fn gfg_printing_compare<Gfgtrait: Debug + Display>(x: &Gfgtrait) {
println!( "Debug value of Trait: `{:?}`" , x);
println!( "Display value of Trait: `{}`" , x);
}
fn main() {
let str = "GeeksforGeeks" ;
let _arr = [10, 20, 30, 40, 50];
let _vec = vec![10, 20, 30, 40, 50];
gfg_printing_compare(&str);
}
|
Output:
Explanation:
In this example, we have imported the use::std::fmt::{Debug, Display} as we are both printing the debug as well as the display trait. In the main function, we have declared str,_arr and_vec and assigned them values respectively. To see the value of the defined trait gfg_printing_compare that we had declared and passed the Gfgtrait and a variable x that refers to it, we call the function gfg_printing_trait to see the printed values.
Example 2:
Rust
# Comparing two trait types using Multiple bounds
#![ allow(unused_variables)]
use std::fmt::Debug;
fn gfg_comparing_types<Gfgtrait: Debug, Debugtrait:
Debug>(x: &Gfgtrait, y: &Debugtrait) {
println!( "Value while passing _arr over x : {:?}" , x);
println!( "Value when we pass _vec over y: {:?}" , y);
}
fn main() {
let str = "GeeksforGeeks" ;
let _arr = [10, 30, 50, 70];
let _vec = vec![20,40,60,80];
gfg_comparing_types(&_arr, &_vec);
}
|
Output:
Explanation:
In this example, we have imported use::std::debug as the only trait so that we can debug the code from a programmer’s context. We have declared a function gfg_compare_types and passed two traits GFG trait and Debug trait. In the main function, we have declared the _arr and _vec and passed them to the compare_type trait. This trait prints the array and the vector from the function gfg_compare_types. To see the value of what they are printing, the compare_types function is called passing the reference of _arr and _vec into it.
Share your thoughts in the comments
Please Login to comment...