Rust 的 switch 语句主要支持以下几种设计模式:
enum Strategy {
Add,
Subtract,
Multiply,
Divide,
}
fn calculate(strategy: Strategy, a: i32, b: i32) -> i32 {
match strategy {
Strategy::Add => a + b,
Strategy::Subtract => a - b,
Strategy::Multiply => a * b,
Strategy::Divide => a / b,
}
}
struct Command {
execute: Box<dyn Fn()>,
}
impl Command {
fn new(execute: Box<dyn Fn()>) -> Command {
Command { execute }
}
fn execute(&self) {
(self.execute)();
}
}
enum Animal {
Dog(String),
Cat(String),
}
trait Visitor {
fn visit_dog(&self, name: &str);
fn visit_cat(&self, name: &str);
}
struct ConcreteVisitor;
impl Visitor for ConcreteVisitor {
fn visit_dog(&self, name: &str) {
println!("Dog: {}", name);
}
fn visit_cat(&self, name: &str) {
println!("Cat: {}", name);
}
}
fn visit(animal: Animal, visitor: &dyn Visitor) {
match animal {
Animal::Dog(name) => visitor.visit_dog(name),
Animal::Cat(name) => visitor.visit_cat(name),
}
}
这些设计模式在 Rust 中都有相应的实现方式,可以根据具体需求选择合适的模式来解决问题。