Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR RUST

armanriazi•rust•trait•blanket

{
*Blanket implementation
Any implementation where a type appears uncovered. impl<T> Foo for T, impl<T> Bar<T> for T, impl<T> Bar<Vec<T>> for T, and impl<T> Bar<T> for Vec<T> are considered blanket impls. However, impl<T> Bar<Vec<T>> for Vec<T> is not a blanket impl, as all instances of T which appear in this impl are covered by Vec.

*Bound
Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint.
}
We can also conditionally implement a trait for any type that implements another trait. Implementations of a trait on any type that satisfies the trait bounds are called blanket implementations and are extensively used in the Rust standard library. For example, the standard library implements the ToString trait on any type that implements the Display trait. The impl block in the standard library looks similar to this code:


impl<T: Display> ToString for T {
    // --snip--
}
Because the standard library has this blanket implementation, we can call the to_string method defined by the ToString trait on any type that implements the Display trait. For example, we can turn integers into their corresponding String values like this because integers implement Display:



let s = 3.to_string();
Blanket implementations appear in the documentation for the trait in the “Implementors” section.
 
PREVIOUS NEXT
Tagged:
ADD COMMENT
Topic
Name
4+7 =