惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

MyScale Blog
MyScale Blog
J
Java Code Geeks
Vercel News
Vercel News
A
About on SuperTechFans
G
Google Developers Blog
C
Check Point Blog
腾讯CDC
N
Netflix TechBlog - Medium
博客园 - 司徒正美
S
SegmentFault 最新的问题
D
DataBreaches.Net
博客园_首页
美团技术团队
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
量子位
雷峰网
雷峰网
IT之家
IT之家
小众软件
小众软件
Blog — PlanetScale
Blog — PlanetScale
博客园 - 三生石上(FineUI控件)
H
Help Net Security
宝玉的分享
宝玉的分享
博客园 - 叶小钗

The Rust Programming Language Forum - Latest posts

What's everyone working on this week (21/2026)? Rust Function Call with one Param Iced + Canvas + Text: How do I create a style for canvas text "Value dropped while borrowed" as a lifetime mismatch Weird `use of moved value` behaviour Slightly surprising behavior of a while loop Clap: how to disable options after a certain positional argument How do i tell rust-analyzer what kind of bracket to use for a macro? Iterator + Borrow Checker: Work around borrowing already borrowed mutable variable Requesting data via mavlink SKILLS.md for Rust development 🧵 Stringlet UTF-8 Hack Option Niche? Iterator + Map - How do divide every element, including the last element, by the last element Why can't we store returned value of a function in a variable if one of the parameters goes out of scope My first crate :D, floop: A more convenient and less error prone replacement for loop `{ select! { .. }}` Sorting is slow because architectures are wrong — zan-sort redesigns the architecture, not the algorithm Iced Font - Create a custom monospace font to display dollar amounts Is the UnsafePinned RFC wrong about being able to return `&mut T` from `get_mut_unchecked`? Fixing Polars 0.37 compilation errors: Hashbrown 0.17 dependency conflict and decimal parsing Any plans for improving error diagnostic in Rust 2.0? How do I build completely offline? Is `&mut T -> &mut ManuallyDrop<T>` well-defined and sound? Would you use this? — fixtura, declarative fake data injection for tests Foreign trait restrictions on native types make generics hard to use Cargo Exclude Directive Compiler reasoning around a modulo counter Multiple mutable references to elements within one vector Handling non-`Send` data in a `Send` closure Review: Static Multi Pool Allocator Rmquickjs - High-level MicroQuickJS bindings for Rust
Basic Object Oriented Programming in Rust
@cyberphone · 2026-04-19 · via The Rust Programming Language Forum - Latest posts

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.