























Yes, I agree. If Dog has many type-specific methods, writing explicit match delegation for every method becomes cumbersome.
I tried another approach, which was already hinted at in one of the comments:
impl Animal {
fn get_speak(&self) -> &dyn Speak {
match self {
Self::Dog(x) => x,
Self::Cat(x) => x,
}
}
}
Here I use pattern matching once to convert Animal into &dyn Speak, and then use that interface:
fn main() {
let dog = Animal::Dog(Dog {});
println!("Animal says: {}", dog.speak());
let speak: &dyn Speak = dog.get_speak();
println!("Speak = {}", speak.speak());
}
That also lets me rewrite Speak for Animal more cleanly:
impl Speak for Animal {
fn speak(&self) -> String {
self.get_speak().speak()
}
}
At first I was concerned about dyn Speak, since trait objects usually imply some runtime overhead through dynamic dispatch and a vtable.
However, when I generated assembly for release mode with:
cargo rustc --release -- --emit asm
the optimizer handled this case quite well. In such a simple example, it was able to remove the obvious overhead, so the generated code was better than I initially expected.
In general, I still think it is worth being careful with dyn if performance is critical. If you are choosing Rust, you likely care about performance already. But in examples like this one, the optimizer can sometimes eliminate much of the cost.
One more thing that may be useful to mention, since this discussion touches Rust enums.
Rust enums are quite different from Java enums. In Java, an enum is mostly a fixed set of named constants, all of the same type. In Rust, an enum is a full data type whose variants can carry different kinds of data.
For example:
enum MyEnum<T> {
StringValue(String),
IntValue(i32),
IntFloatValue(i32, f32),
CustomValue(T),
}
And then pattern matching becomes very natural:
use std::fmt::Debug;
fn print_enum<T: Debug>(enum_value: &MyEnum<T>) {
match enum_value {
MyEnum::StringValue(x) => println!("StringValue = {}", x),
MyEnum::IntValue(x) => println!("IntValue = {}", x),
MyEnum::IntFloatValue(x, y) => println!("IntValue = {}, FloatValue = {}", x, y),
MyEnum::CustomValue(x) => println!("CustomValue = {:?}", x),
}
}
Usage:
print_enum(&MyEnum::<Vec<i32>>::StringValue("string".to_owned()));
print_enum(&MyEnum::<Vec<i32>>::IntValue(6));
print_enum(&MyEnum::<Vec<i32>>::IntFloatValue(5, 1.0));
print_enum(&MyEnum::<Vec<i32>>::CustomValue(vec![1, 2, 3]));
So in Rust, an enum is not just a symbolic constant. It is more like a tagged union or algebraic data type. In this example, it is not just used as a constant, but also carries data that is later used in pattern matching.
The key idea is not “we chose enum, so we must use pattern matching,” but rather the opposite: if pattern matching is a natural fit for the problem, then enum is usually the right tool.
In your original example, if pattern matching starts to feel awkward, that is often a signal that enum might not be the best abstraction there. In such cases, it may be worth looking at other approaches, such as trait-based design or generics, depending on what you are trying to model.
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。