Fluent Rust - Trait bounds and conditional implementation

Migo·2023년 8월 21일
0

Fluent Rust

목록 보기
3/27
post-thumbnail

Using a trait bound with an impl, we can implement methods conditionally for types that implement the specified traits.

struct Point<T,U>{
		x: T,
		y: U

}

impl<T,U> Point<T,U> {
		fn new(x:T, y:U) -> Self{
				Self{x,y}		
		}
}

Here, we implement a method new that takes type T which could be any type.

Trait bounds

But say, if you want to make the struct comparable based on the field’s value, it must be clear that the type of the field is comparable. And the comparison method should be on those ‘comparable’ types.

impl<T:Add+Debug,U:Add+Debug> Point<T,U>{
    pub fn method_with_caculatable_values(&self){
        println!("{self:?}");
    }
}

Here, we use trait bounds to tell Rust compiler that “I’m implementing a method for the types T and U that implement Add and Debug traits.”

And if you put values that are not Add-able, you don’t get to access the method_with_calculatable_values method from that object. So the following code will error out:

let point = Point::new(vec![1,2,3,4],vec![3,5,6,7]); //new() is accessible to any type.
point.method_with_caculatable_values(); // this will error out.

If you instead initialize Point with Add-able values, it goes fine:

profile
Dude with existential crisis

0개의 댓글

관련 채용 정보