Constrained genericity: Difference between revisions
Content added Content deleted
(Added Rust language) |
|||
Line 1,263: | Line 1,263: | ||
// This declares the generic "FoodBox" type, |
// This declares the generic "FoodBox" type, |
||
// whose parameter must "Eatable" constraint. |
// whose parameter must satisfy the "Eatable" constraint. |
||
// The objects of this type contain a vector of eatable objects. |
// The objects of this type contain a vector of eatable objects. |
||
struct FoodBox<T: Eatable> { |
struct FoodBox<T: Eatable> { |
||
Line 1,269: | Line 1,269: | ||
} |
} |
||
// This implements the functions associated |
// This implements the functions associated with the "FoodBox" type. |
||
// |
// This statement is not required, but here it is used |
||
// to declare a handy "new" constructor. |
// to declare a handy "new" constructor. |
||
impl<T: Eatable> FoodBox<T> { |
impl<T: Eatable> FoodBox<T> { |
||
Line 1,288: | Line 1,288: | ||
} |
} |
||
// This makes the primitive "char" type satisfy the "Eatable" constraint. |
// This makes also the primitive "char" type satisfy the "Eatable" constraint. |
||
impl Eatable for char { |
impl Eatable for char { |
||
fn eat() {} |
fn eat() {} |
||
Line 1,299: | Line 1,299: | ||
// This instantiate a "FoodBox" parameterized by the "char" type. |
// This instantiate a "FoodBox" parameterized by the "char" type. |
||
// It is allowed as "char" implements "Eatable". |
// It is allowed, as "char" implements "Eatable". |
||
let _fb2 = FoodBox::<char>::new(); |
let _fb2 = FoodBox::<char>::new(); |
||
// This instantiate a "FoodBox" parameterized by the "bool" type. |
// This instantiate a "FoodBox" parameterized by the "bool" type. |
||
// It is NOT allowed as "bool" does not implement "Eatable". |
// It is NOT allowed, as "bool" does not implement "Eatable". |
||
//let _fb3 = FoodBox::<bool>::new(); |
//let _fb3 = FoodBox::<bool>::new(); |
||
} |
} |