Jump to content

Constrained genericity: Difference between revisions

m
(Added Rust language)
Line 1,263:
 
// This declares the generic "FoodBox" type,
// whose parameter must satisfy the "Eatable" constraint.
// The objects of this type contain a vector of eatable objects.
struct FoodBox<T: Eatable> {
Line 1,269:
}
 
// This implements the functions associated towith the "FoodBox" type.
// ItThis statement is not required, but here it is used
// to declare a handy "new" constructor.
impl<T: Eatable> FoodBox<T> {
Line 1,288:
}
 
// This makes also the primitive "char" type satisfy the "Eatable" constraint.
impl Eatable for char {
fn eat() {}
Line 1,299:
 
// This instantiate a "FoodBox" parameterized by the "char" type.
// It is allowed, as "char" implements "Eatable".
let _fb2 = FoodBox::<char>::new();
 
// This instantiate a "FoodBox" parameterized by the "bool" type.
// It is NOT allowed, as "bool" does not implement "Eatable".
//let _fb3 = FoodBox::<bool>::new();
}
Cookies help us deliver our services. By using our services, you agree to our use of cookies.