Living a purposeful life - Karmyog... Salvation... Awakening...
You know, the best way to learn a modern computer programming language is to apply the nuances in designing a real life problem. This way I learned C++, Java and Python. And now I am applying the same logic while picking up Rust.
in Rust I keep my trust...
So...
here we go...
A simple factory design pattern in Rust - my second program of Rust.
Enjoy...
Source Code:
trait Food{
fn display(&self);
}
enum FoodType{
Chocolate,
Biscuit,
}
struct Chocolate{}
impl Food for Chocolate {
fn display(&self) {
println!("A chocolate is made...");
}
}
struct Biscuit{}
impl Food for Biscuit {
fn display(&self){
println!("A biscuit is made...");
}
}
struct FoodFactory;
impl FoodFactory{
fn new_food (item:&FoodType) -> Box<dyn Food>{
match item {
FoodType::Chocolate => Box::new(Chocolate{}),
FoodType::Biscuit => Box ::new(Biscuit{}),
}
}
}
fn main() {
let food = FoodFactory::new_food(&FoodType::Chocolate);
food.display();
let food = FoodFactory::new_food(&FoodType::Biscuit);
food.display();
}
No comments:
Post a Comment