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

推荐订阅源

Microsoft Azure Blog
Microsoft Azure Blog
V
V2EX
博客园 - 【当耐特】
WordPress大学
WordPress大学
爱范儿
爱范儿
美团技术团队
宝玉的分享
宝玉的分享
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
量子位
Hugging Face - Blog
Hugging Face - Blog
B
Blog RSS Feed
Recorded Future
Recorded Future
Engineering at Meta
Engineering at Meta
雷峰网
雷峰网
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
M
MIT News - Artificial intelligence
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
腾讯CDC
大猫的无限游戏
大猫的无限游戏
Jina AI
Jina AI
博客园 - 叶小钗
GbyAI
GbyAI
Y
Y Combinator Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Full Disclosure
G
Google Developers Blog
D
Docker
T
Tailwind CSS Blog
C
Check Point Blog
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
T
The Blog of Author Tim Ferriss
B
Blog
博客园 - 三生石上(FineUI控件)
博客园 - Franky
H
Help Net Security
MyScale Blog
MyScale Blog
U
Unit 42
D
DataBreaches.Net
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
I
InfoQ
阮一峰的网络日志
阮一峰的网络日志
The GitHub Blog
The GitHub Blog
L
LangChain Blog
有赞技术团队
有赞技术团队
Martin Fowler
Martin Fowler
Microsoft Security Blog
Microsoft Security Blog

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 Iced + Rusqlite + Chrono: Problem with custom error type Why can&#39;t the Rust compiler infer the T type parameter in this BTreeMap::range call? Beginner building a Rust backend framework (AI-assisted) — feedback appreciated C++ to Rust -- Exceptions Re-exporting a trait with a custom derive_macro Gold linker is deprecated Why is using PhantomData valid in this case? Code review for Static Pool Allocator Discussion on Synchronous Crate Concurrency Refactor using Stackful Coroutines Model in Rust Can a future used only by `async fn` assume it won&#39;t be polled again after becoming ready? High-performance `fast-powi` crate Looking for a pool based allocator Why is this legal? What does it mean for Rustc to run "out of TLS keys"? Using async/await internally with no internal runtime, but exposing a nonblocking poll API — is this a reasonable design? Testing functions that use randomness `cargo-path`: improve coding agents&#39; ability to find Rust documentation Rust task runners Lifetime weird case Windows - USB device not detected A random rustc-ice-[...].txt file appeared Develop rust where the environment is setup in a docker Undefined Behavior: in-bounds pointer arithmetic failed: attempting to offset pointer by 20 bytes, but got alloc238 which is only 1 byte from the end of the allocation Unbug 0.5 - Runtime debug assertions Is there a tiny error in section 6.2 Reference types? Vasya go to (his) Home 🏡 Lifetime woes implementing ratatui::Widget for a reference Rusqlite + Chrono: How do I simplify code to obtain chrono datetime value From OOP to Rust – struggling with code organization and data structure design Way to avoid a self-referential struct Rust RF and audio resources/communities Whyhttp - HTTP mocks that fail where the bug actually is Using tokio channel permits in a tower service Arc::increment_strong_count design question (cross-post) `&T`, `&mut T`, `Pin<&mut T>` and `&Cell<T>`: Ways of Borrowing a `T` Ratatui detect arrow key press and release Feedback about post in medium Debugger not showing/offering variables? nestrs: a NestJS-style framework for Rust built on Axum and Tower Confusion about struct variance with &mut dyn How do I do hmr in rust How to call struct method as function pointer in loop Loops inside loops and mutable reference on Iterator VSCode - rust-analyzer - annoying re-builds due to RUSTC_BOOTSTRAP changed Borsh v1.6.1 example What's everyone working on this week (14/2026)? What's everyone working on this week (17/2026)? RawWakerVTable functions, did I write them correctly? Cargo test's verbose output - can I quiet it? Sem: semantic entity level version control CLI built with tree-sitter How do i get all the words in a string and convert it into a vector? Looking for feedback on my first tokenizer in Rust Frostmirror - (lightweight airgap alternative inspired from panamax and romt) - an offline cargo repository for airgap system that can be deployed through a docker image Does "ill-formed, no diagnostic required" exist in Rust? If a program is built with software floating-point emulation, is it affected by hardware floating-point environment? Rustc-link-lib static library How does crates.io and docs.rs store crates? Various input in one line error[E0080]: index out of bounds error when trying to install LuaCAD CSV to SQLite - Is it better to write records as they are being read Looking for feedback for a graph-based task scheduler This is my first project. I invented a new algorithm that even AI don't know. It's about bigint. And I'm 15. Thanks for watching. By the way, my crate named `nna` Why Windows rustc uses a different color scheme? Clap completion question Is RMW operation less prone to reading stale values than a pure load? Why are builds of my crate's test not consistent (cargo build vs cargo test vs VSCode-Test-Explorer) Type inference of generic parameters Cyw43 on STM32H723 Reducing code repetition with Vecs and fields Are there any object detection libraries out there for the Arduino?
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.