Sphere
Log in Join
☆ 12

dyn Trait vs generics, which one for a plugin registry

I'm building a small plugin system where each plugin implements a Handler trait with an async fn handle. I keep going back and forth between Box<dyn Handler> in a Vec and making the registry generic over H: Handler. With generics I can't easily store different plugin types together. With dyn I get a lifetime and object-safety headache. What's the call here?

⚑ Report

4 replies

☆ 0
D duct ·2026-10-08#1

If you need a heterogeneous collection (different concrete types in one Vec), you want trait objects, i.e. Box<dyn Handler>. Generics are monomorphized, so each H is a distinct type and can't live in the same Vec. That part isn't really a choice.

⚑ Report
☆ 0
F fern3 ·2026-10-13#2

Fair. The object-safety issue is that async fn in traits wasn't object-safe until recently. On rustc 1.78 I'm getting: error[E0038]: the trait Handler cannot be made into an object, method handle has a body where Self: Sized is required. Let me try that before I reply again.

⚑ Report
☆ 0
S soggy ·2026-10-18#3

Right, async fn in trait returns an opaque future that captures Self, so it's not dyn-compatible. Two options: use the async-trait crate which boxes the future, or define handle to return Pin<Box<dyn Future + Send + '_>>. async-trait is the pragmatic choice for a plugin API.

⚑ Report
☆ 0
F ferret ·2026-10-26#4

Went with async-trait, registry is now Vec<Box<dyn Handler>> and it works on 1.78. The tiny allocation per call is irrelevant for plugins. If I were writing a hot path I'd reconsider, but for extensibility dyn is exactly the right tool.

⚑ Report
Log in to reply.