Zeeshan Adil
Book a call
← Rust for C# Engineers: From Garbage Collection to Ownership and Lifetimes

Chapter 8 of 16 · Part II, Working knowledge

Generics that compile to what you would have written by hand

by Zeeshan AdilUpdated 30 min read
Listen to this articleRust Generics vs C# Generics: Monomorphization and dyn 31 min · read by an AI voice
0:00 / 31:18

How Rust monomorphizes generics where the CLR shares code, when to choose dyn Trait and its vtable, impl Trait, dyn compatibility and what dispatch costs.

This chapter assumes traits are familiar. The practical goal is choosing between a generic parameter, impl Trait, and dyn Trait. Read the basic implementations and decision table first; the CLR dispatch and binary-size sections explain the tradeoffs in more depth.

Rust and C# generics can look similar at the call site, but their implementation and tradeoffs differ. Let's start with what the compiler generates.

Code
fn largest<T: PartialOrd>(items: &[T]) -> &T {
    let mut best = &items[0];
    for item in items {
        if item > best { best = item; }
    }
    best
}

T: PartialOrd fills a similar role to a C# comparison constraint, but the contracts differ. Rust separates partial ordering (PartialOrd) from total ordering (Ord). Floating-point NaN is unordered under PartialOrd, so f64 does not implement Ord. C#'s Double.CompareTo defines an ordering even for NaN; it is not equivalent to the floating-point < and > operators. Longer Rust bounds can move into a where clause to keep the signature readable.

Both languages check the body of the generic function against the declared bounds, at the definition, before anyone calls it. Use > inside largest without declaring PartialOrd and you get an error in largest, not at some distant call site. That is the same contract C# gives you, and it is worth saying out loud, because the third member of this family does not offer it. C++ templates are checked once the arguments are known, which is where the famous walls of instantiation errors come from. Rust and C# agree on the front half of the design. They disagree completely on the back half.

Where clauses reach further than C# constraints

C# constraints come from a fixed grammar. A base class or interface list, plus class, struct, notnull, unmanaged, default, new(), and the allows ref struct anti-constraint, in a documented order, and every one of them constrains a type parameter you declared.

Rust supports trait and lifetime bounds, and its where clauses can constrain more than a bare type parameter.

Code
use std::fmt::Display;

fn summarize<I>(items: I) -> String
where
    I: IntoIterator,
    I::Item: Display,
    Vec<I::Item>: Default,
{
    let mut out = String::new();
    for item in items {
        out.push_str(&format!("{item} "));
    }
    out
}

I::Item: Display bounds an associated type of a parameter. C# cannot say that: there is no way to write "T is a sequence of something printable" without expressing the element relationship through an additional type parameter or another API design. C# can infer type arguments in some call shapes, so callers do not always have to spell them out. Vec<I::Item>: Default bounds a concrete type built out of a parameter, which C# also has no syntax for. And Rust has higher-ranked bounds, where F: for<'a> Fn(&'a str) -> &'a str, which say the bound holds for every lifetime rather than for one the caller picked.

Going the other way, some C# constraints have no Rust spelling because Rust has nothing for them to constrain. new() has no equivalent, because Rust has no constructors; you write T: Default and call T::default(), which is an ordinary trait bound. The class versus struct split does not exist, because Rust has no such split to make. And allows ref struct exists because C# needs a way to tell a generic method it must obey ref safety rules for T, which in Rust is not opt-in and not a constraint, it is what the borrow checker does to every type.

There is one constraint in Rust you did not write and it is on almost everything. Every type parameter carries an implicit Sized bound. You opt out with ?Sized, which is why that appears all through the standard library. Forget it and E0277 tells you the size cannot be known at compile time, which is usually the moment a C# engineer discovers that dyn Trait is not something you can store by value.

The compiler writes the copies for you

The real difference is what the compiler does with largest.

The strongest evidence that a generic function has no run-time existence in Rust is that you cannot give one a stable exported name. Ask for one and the compiler tells you the request is meaningless.

Code
#[unsafe(no_mangle)]
pub fn foo<T>() {}
Code
warning: functions generic over types or consts must be mangled
 --> src/lib.rs:2:1
  |
1 | #[unsafe(no_mangle)]
  | -------------------- help: remove this attribute
2 | pub fn foo<T>() {}
  | ^^^^^^^^^^^^^^^
  |
  = note: `#[warn(no_mangle_generic_items)]` on by default

That is the no_mangle_generic_items lint, warn by default rather than a hard error, and its explanation is blunt: the attribute has no effect here and should be removed. In editions before 2024 the attribute is spelled #[no_mangle] without the unsafe wrapper, and the lint fires the same way.

There is no symbol called foo to export, because there is no function called foo in the object file. There are only foo::<u8>, foo::<String>, and whatever else you instantiated, each with the type arguments baked into its mangled name.

Compare that with C#, where typeof(T) inside a generic method returns a real Type because the runtime genuinely has one. Rust's nearest equivalent, std::any::type_name, is resolved at compile time and its documentation is explicit that the output carries no stability guarantee and is meant for diagnostics only. That is the philosophical gap in one API.

The model above is too simple

One copy per type argument is the right first model, and it is wrong in four ways that matter once your build gets slow.

It is one copy per reachable instantiation, not per type. Before codegen, rustc runs a monomorphization collector that walks outward from roots and builds the list of concrete items that actually need machine code. A generic function nobody calls costs nothing. A generic function called from three places at the same type costs one copy.

Lifetimes are erased entirely. Type parameters produce copies. Lifetime parameters do not, and never have. A function generic over 'a compiles once. This is easy to miss, and it is why lifetime-heavy code is not, by itself, a compile-time problem.

Copies get shared, but only in some builds. rustc has a share_generics mode that lets a crate reuse instantiations already emitted upstream instead of stamping out its own. In the compiler's own configuration code the default is on at opt-level 0, 1, s, and z, and off at opt-level 2 and 3. In plain terms: cargo build shares, cargo build --release does not. The trade is that a local copy can be optimized against its call site and a shared one cannot, which matters more the harder you are optimizing. It is one of several reasons a release build has more code to chew through than a debug build.

The cost lands in your crate, not the library's. The dev guide's codegen unit partitioning table is blunt about it: for a generic function in a dependency, regardless of inlining, all monomorphized instances appear in a single codegen unit of the crate that used them. A library with a wide generic API surface does not pay for that. You do, every time you build.

What .NET does instead

.NET sits between erasure and monomorphization, and it picks per type argument.

For value type arguments the runtime specializes. Microsoft's documentation of generics at run time says the runtime creates a specialized generic type with the value type substituted into the CIL, once per unique value type, which is why List<int> really does store unboxed integers.

For reference type arguments it shares. The type loader chapter of the Book of the Runtime names the mechanism: every reference-type argument is replaced by an internal type called System.__Canon, and the resulting canonical instantiation stands in for all of them. List<string> and List<object> are distinct types with their own method tables, and they share one EEClass and one set of compiled method bodies, because all references are the same size and the layouts are identical. Constraint checking has to be special-cased to ignore the fact that __Canon satisfies nothing.

Sharing is not free, and the shared generics design document shows what it costs. Where a specialized body would hardcode a type handle:

Code
mov rcx, type handle of List<string>
call ToString()
ret

the shared body has to go and find it:

Code
mov rcx, generic context
mov rcx, [rcx + offset of InstantiatedMethodDesc::m_pPerInstInfo]
mov rcx, [rcx + dictionary slot containing type handle of List<T>]
call ToString()
ret

The shared body may need dictionary lookups where specialized code could use a concrete type directly. The number of loads and whether they survive optimization depend on the operation and runtime. This sharing saves generated code while preserving runtime type information. Rust monomorphizes the chosen instantiations ahead of time; ordinary Rust generics cannot create a new instantiation from a runtime type descriptor.

So the bill:

CaseRust.NET
Value type argumentsspecialized copyspecialized copy
Reference type argumentsspecialized copyone shared canonical body
Boxing at the boundarynot required by monomorphization; explicit boxes and allocating callees remain possibleoften avoidable in specialized code; converting a struct to an interface can box
typeof(T) at run timeno such thingworks
Cost of knowing Tzerodictionary indirection in shared code
New instantiation at run timeimpossibleroutine
Where the cost landsyour binary and your buildJIT time and working set

Monomorphization lets the compiler resolve generic calls for concrete types and often inline across that boundary. It does not prohibit allocation or guarantee inlining. A generic function can call Box::new, invoke allocating library code, or receive a trait object through a reference.

What you pay: binary size, since ten instantiations mean ten copies, and compile time, since every one of those copies has to be optimized and emitted. How much depends entirely on how many instantiations your crate graph reaches, and cargo llvm-lines, further down, is how you find that out rather than guess at it.

When you want the vtable instead

Sometimes you genuinely need a heterogeneous collection, which monomorphization cannot give you because the concrete types differ at run time. That is what dyn is for. Here is a complete program that uses both strategies on the same trait, which you can paste into main.rs and run:

Code
use std::mem::size_of;

struct Request {
    path: String,
    tenant: u32,
    bytes: usize,
}

trait Policy {
    fn name(&self) -> &'static str;
    fn allows(&self, req: &Request) -> bool;
}

struct MaxBody { limit: usize }
struct BlockedPaths { paths: Vec<&'static str> }
struct TenantQuota { tenant: u32, max_bytes: usize }

impl Policy for MaxBody {
    fn name(&self) -> &'static str { "max_body" }
    fn allows(&self, req: &Request) -> bool { req.bytes <= self.limit }
}

impl Policy for BlockedPaths {
    fn name(&self) -> &'static str { "blocked_paths" }
    fn allows(&self, req: &Request) -> bool {
        !self.paths.iter().any(|p| *p == req.path.as_str())
    }
}

impl Policy for TenantQuota {
    fn name(&self) -> &'static str { "tenant_quota" }
    fn allows(&self, req: &Request) -> bool {
        req.tenant != self.tenant || req.bytes <= self.max_bytes
    }
}

// Static. One machine-code copy per concrete P. The call to `allows` is
// direct, and the optimizer may inline it.
fn enforce<P: Policy>(policy: &P, req: &Request) -> bool {
    if policy.allows(req) {
        return true;
    }
    println!("rejected by {}", policy.name());
    false
}

// Dynamic. One machine-code copy total. The call to `allows` is an
// indirect call through a vtable.
fn enforce_all(policies: &[Box<dyn Policy>], req: &Request) -> bool {
    let mut ok = true;
    for policy in policies {
        if !policy.allows(req) {
            println!("rejected by {}", policy.name());
            ok = false;
        }
    }
    ok
}

fn main() {
    let req = Request { path: "/v1/scrape".to_string(), tenant: 7, bytes: 4096 };

    println!("static:  {}", enforce(&MaxBody { limit: 1024 }, &req));

    let chain: Vec<Box<dyn Policy>> = vec![
        Box::new(MaxBody { limit: 8192 }),
        Box::new(BlockedPaths { paths: vec!["/admin"] }),
        Box::new(TenantQuota { tenant: 7, max_bytes: 2048 }),
    ];
    println!("dynamic: {}", enforce_all(&chain, &req));

    println!("&MaxBody        {} bytes", size_of::<&MaxBody>());
    println!("&dyn Policy     {} bytes", size_of::<&dyn Policy>());
    println!("Box<dyn Policy> {} bytes", size_of::<Box<dyn Policy>>());
}

The last three lines are the point. On a 64-bit target you get 8, 16, and 16. A reference to a concrete type is one machine word. A reference to a trait object is two.

The vtable holds more than function pointers. The standard library's DynMetadata, the nightly API for reaching one directly, documents the contents as the type's size, its alignment, a pointer to its drop_in_place, and then pointers to the trait's methods. Size and alignment are in there because dropping and deallocating a trait object requires knowing how big the thing behind the pointer actually is, and nothing else in the program knows.

One vtable exists per trait implementation, per the E0038 explanation. Not per type. MaxBody as dyn Policy and MaxBody as dyn Debug are two different vtables, and the pairing lives in the pointer, not in the value.

Because the vtable is chosen when the fat pointer is built, you cannot generally convert a &dyn A into a &dyn B. Supertrait upcasting has worked since Rust 1.86, so &dyn Trait coerces to &dyn Supertrait when Supertrait is actually a declared supertrait. Write trait MyTrait: Any and you can upcast to dyn Any and downcast from there, which the release notes call out as the useful case. That is the whole story, and it is a small story next to what a C# interface reference can do.

CLR interface dispatch is a different animal

It is tempting to say a dyn call is an interface call. The shapes are close and the mechanisms are not.

A C# object reference is one word. The object it points at begins with a pointer to its method table, so a List<IPolicy> is an array of single-word references and every element carries its own type with it. That is why is, as, and pattern matching on interfaces cost so little structurally: the object already knows everything.

Interface calls do not go through a classic vtable. CoreCLR uses virtual stub dispatch, and the design document is clear that although the mechanism could handle both, it is currently used only for interface dispatch, with plain virtual calls still using a real vtable. A call site starts on a lookup stub, which asks the resolver and back-patches itself. If the site looks monomorphic it gets a dispatch stub, which compares the receiver's method table against one cached value and jumps straight to the cached target. If that comparison keeps failing, the site is demoted to a resolve stub, which hashes the token and type into a global cache.

So a hot, monomorphic interface call in .NET is a compare, a well-predicted branch, and a jump to the cached target. A dyn call in Rust is a load and an indirect call with no guard at all. Neither is obviously cheaper, and if the site is polymorphic in .NET, the hash lookup makes Rust's unconditional indirect call look good.

The JIT can also use observations from the running process. Guarded devirtualization places a type check before a specialized path and retains the general call as a fallback. Dynamic profile-guided optimization supplies observations about which receiver types actually appear. This lets .NET adapt code after the application starts.

Rust usually makes that decision ahead of time. LLVM can devirtualize when it can identify a target, and rustc also supports profile-guided optimization using data from earlier runs. The difference is when the feedback is applied: a Rust PGO workflow rebuilds the binary, while .NET's JIT can specialize during execution.

That is a real advantage for the CLR, and it is the advantage of having a compiler running inside your process.

Being honest about what dispatch costs

The indirect call is not the expensive part.

On a modern out-of-order core, an indirect call whose target is stable is predicted, and the load of the vtable entry overlaps with everything around it. If the call happens once per HTTP request, it is invisible next to the syscall you are about to make.

The larger cost can be the optimization you lose. If the compiler cannot resolve the target, it generally cannot inline the body and optimize across that call. Static analysis or profile-guided specialization may recover those opportunities, so an indirect call is a possible optimization barrier rather than an absolute one.

Which means the cost scales with two things: how small the callee is, and how many times you call it. A dyn Iterator in the inner loop of a numeric kernel is a genuine problem, because the body you failed to inline is a few instructions and the loop runs a very large number of times. A Box<dyn Policy> chain evaluated once per request sits under everything else the request does, and designing around it puts effort in the wrong place.

A practical rule: default to generics, and reach for dyn when you need a collection of mixed types, when you are crossing a plugin boundary, or when the instantiation count is getting silly and you would rather have the smaller binary. The dispatch cost is real but small, and it is rarely the reason something is slow. Do not contort a design to avoid a vtable.

Dyn compatibility, previously called object safety

Not every trait can be a trait object, and the reason is always the same. There has to be a single vtable that works for every implementor.

Add a method with a generic parameter to Policy and the compiler stops you:

Code
trait Policy {
    fn name(&self) -> &'static str;
    fn allows(&self, req: &Request) -> bool;
    fn log<W: std::io::Write>(&self, out: &mut W);
}
Code
error[E0038]: the trait `Policy` is not dyn compatible
  --> src/main.rs:41:32
   |
41 | fn enforce_all(policies: &[Box<dyn Policy>], req: &Request) -> bool {
   |                                ^^^^^^^^^^ `Policy` is not dyn compatible
   |
note: for a trait to be dyn compatible it needs to allow building a vtable
      for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
  --> src/main.rs:11:8
   |
 8 | trait Policy {
   |       ------ this trait is not dyn compatible...
...
11 |     fn log<W: std::io::Write>(&self, out: &mut W);
   |        ^^^ ...because method `log` has generic type parameters
   = help: consider moving `log` to another trait

The mechanism is the one from the first half of this section. log is monomorphized per W, so a vtable would need one slot per W anyone might ever use, and that set is unbounded and not known when the vtable is built.

The reference lists the rules, and each has the same shape of justification.

  • No Self: Sized, directly or from a supertrait. This one is subtle and the E0038 explanation spells it out. Rust guarantees that dyn Trait itself implements Trait, so that a &dyn Trait can be handed to a function taking T: Trait + ?Sized. But dyn Trait is unsized, so it can never implement a trait requiring Self: Sized. Rather than carve out an exception to that guarantee, Rust forbids the trait object.
  • No Self in a method except as the receiver. fn clone_me(&self) -> Self has no single answer through a trait object, which is why Clone cannot be used as dyn Clone.
  • No type or const parameters on a method. The one above. Lifetime parameters are fine, because they are erased and produce no extra vtable slots.
  • No associated constants, and no associated types that take generics.
  • Receivers must come from a fixed set: &self, &mut self, Box<Self>, Rc<Self>, Arc<Self>, or a Pin of one of those. A nested receiver like Rc<Box<Self>> is out.
  • No opaque return types, which is why an async fn in a trait and a method returning impl Trait both make the trait dyn incompatible. That is the root of the rough edge you will meet later with async traits.

The escape hatch is worth memorizing, because it turns most of these from a redesign into a one-line fix. Put where Self: Sized on the offending method and it becomes explicitly non-dispatchable: the trait is dyn compatible again, the method is unavailable on trait objects, and every concrete implementor keeps it.

Code
trait Policy {
    fn name(&self) -> &'static str;
    fn allows(&self, req: &Request) -> bool;
    fn log<W: std::io::Write>(&self, out: &mut W) where Self: Sized;
}

C# has the same rule now, for the same reason. Static abstract interface members arrived in C# 11 to make generic math work, and they can only be reached through a type parameter. Call one on an interface-typed variable and you get:

Code
error CS8926: A static virtual or abstract interface member can be accessed only on a type parameter.

No receiver means no entry in a dispatch table, in either language. The difference is which side of the line each language drew first. C# always had run-time dispatch and had to add a static-only escape. Rust always had static dispatch and had to add rules for what may become dynamic.

Underneath both sets of rules is one asymmetry. .NET's dispatch machinery can grow at run time, because the runtime is a compiler and can produce a new instantiation the first time it sees one. Rust's vtable is finished at link time. Every dyn compatibility rule follows from that.

impl Trait, in both positions

impl Trait is a way of not naming a type. It is not a third dispatch strategy sitting alongside generics and dyn.

In return position, fn checks() -> impl Iterator<Item = String> hides one concrete return type per instantiation. That avoids requiring dynamic dispatch or boxing just to hide the type. The returned iterator and its items may still allocate, and changing observable properties such as auto traits can still break callers.

The "exactly one" is enforced, and the diagnostic says so directly:

Code
trait Encoder {}
impl Encoder for u8 {}
impl Encoder for u16 {}

fn pick(wide: bool) -> impl Encoder {
    if wide {
        return 0_u16;
    }
    0_u8
}
Code
error[E0308]: mismatched types
 --> src/main.rs:9:5
  |
5 | fn pick(wide: bool) -> impl Encoder {
  |                        ------------ expected a single type implementing `Encoder` because of return type
6 |     if wide {
7 |         return 0_u16;
  |                ----- return type resolved to be `u16`
8 |     }
9 |     0_u8
  |     ^^^^ expected `u16`, found `u8`

For different branch types, you can use an enum that implements Encoder, or return a boxed trait object. The enum keeps the set of alternatives explicit; the box supports an open set of implementations.

This is where the iterator story lands. In Rust, .iter().filter(f).map(g) has the concrete type Map<Filter<Iter<'_, T>, F>, G>, a real struct nested three deep, and every next is a direct call the optimizer can inline until the whole chain collapses into one loop. Nobody wants to write that type in a signature, so you write -> impl Iterator<Item = U> and the concrete type stays hidden and stays static.

C# has no equivalent. Returning IEnumerable<T> hands the caller an interface reference, and every MoveNext is an interface call the JIT may or may not devirtualize depending on what the profile saw. That is a deliberate trade in LINQ's design and it buys real things, including the ability to swap in a different pipeline at run time. It is also why impl Trait has no C# spelling: there is no way in C# to say "a concrete type I will not name."

Return-position impl Trait inside a trait desugars to an anonymous associated type, which is exactly why it makes the trait dyn incompatible. And Rust 2024 changed the default lifetime capture rules for impl Trait in return position, so if you are reading older code the edition guide chapter is the reference.

The decision table

PropertyGeneric T, or impl Trait argument-> impl Traitdyn Trait
Type chosen bythe callerthe calleerun time
Dispatchdirect, inlinabledirect, inlinableindirect, through a vtable
Machine codespecialized per reachable instantiation, subject to optimizationconcrete implementation, possibly specialized by generic inputsshared caller code plus concrete implementations and vtables
Representationdepends on the concrete type; need not be a pointerdepends on the hidden concrete typea reference to a trait object currently carries data and vtable pointers
Heterogeneous collectionnonoyes
Allocation impliednone by the dispatch strategynone by hiding the typenone for &dyn Trait; Box<dyn Trait> adds owned storage
Works with generic methodsyesyesno, E0038
Nearest C#where T : IPolicy with a struct argumentnothinginterface reference, or where T : IPolicy with a class argument

Binary size, and the trick the standard library uses

Binary size is where monomorphization stops being an abstraction. The pattern that causes it is a wide, convenient generic API: every entry point taking impl AsRef<Path> or impl Into<String> for the caller's comfort, and every one of those stamping out a copy of a large function body per argument type.

The standard library solves this in a way worth copying. OpenOptions::open is generic and its body is one line:

Code
pub fn open<P: AsRef<Path>>(&self, path: P) -> io::Result<File> {
    self._open(path.as_ref())
}

fn _open(&self, path: &Path) -> io::Result<File> {
    // the actual work, compiled exactly once
}

The generic shell exists only to convert, and it inlines to nothing. The body lives in a non-generic inner function compiled once, however many argument types callers use. If you have a generic function longer than a few lines and called with many types, this split is the first thing to try, and cargo llvm-lines will tell you which functions to try it on.

The compile-time story compounds the same way. Since a dependency's generic code is codegen'd in your crate, a graph full of generic-heavy libraries costs you build time in proportion to how many instantiations you reach, not how large the libraries are.

The .NET version of this bill exists, and you only see it when you take the JIT away. The Native AOT documentation says it plainly: generic parameters substituted with struct type arguments get specialized code per instantiation, the dynamic runtime generates many of those on demand, and Native AOT has to pre-generate all of them, which can have significant impact on the disk size of the application. That is Rust's trade-off arriving in .NET, for the same underlying reason. It is also why heavily generic, reflection-driven .NET code is the hardest kind to move to AOT: the constraints a Native AOT migration imposes and the constraints Rust imposes are close cousins.

Two dispatch habits worth unlearning

Reaching for Box<dyn Trait> because an interface always meant run-time polymorphism. This is the big one. In C# the interface is the dispatch mechanism, so the habit is to type every parameter as the interface. In Rust the default should be fn thing<P: Policy>(p: &P) or fn thing(p: impl Policy), and dyn should be a decision you made on purpose. Recognize it when every field on your struct is a Box<dyn Something> and none of them is ever a mixed collection.

Assuming a C# constraint gives you static dispatch. The mirror mistake, and the more expensive one. A method declared where TPolicy : IPolicy looks specialized, and with a class argument it is not: the shared canonical body has no way to know the type, so the call is a genuine interface dispatch. Make the type argument a struct and the picture changes completely. The C# compiler emits the call with the constrained. prefix, and the documented semantics are that when the type is a value type implementing the method, the pointer is passed unmodified to a direct call with no boxing.

Here is the same program in C#, and the only line that really matters is which of the three policies is a struct.

Code
using System;
using System.Collections.Generic;

record Request(string Path, uint Tenant, int Bytes);

interface IPolicy
{
    string Name { get; }
    bool Allows(Request req);
}

sealed class MaxBody(int limit) : IPolicy
{
    public string Name => "max_body";
    public bool Allows(Request req) => req.Bytes <= limit;
}

sealed class BlockedPaths(params string[] paths) : IPolicy
{
    public string Name => "blocked_paths";
    public bool Allows(Request req) => Array.IndexOf(paths, req.Path) < 0;
}

readonly struct TenantQuota(uint tenant, int maxBytes) : IPolicy
{
    public string Name => "tenant_quota";
    public bool Allows(Request req) => req.Tenant != tenant || req.Bytes <= maxBytes;
}

static class Enforcer
{
    // Specialized only when TPolicy is a value type. With a class argument
    // this runs the shared __Canon body and Allows is a real interface call.
    public static bool Enforce<TPolicy>(TPolicy policy, Request req)
        where TPolicy : IPolicy
    {
        if (policy.Allows(req)) return true;
        Console.WriteLine($"rejected by {policy.Name}");
        return false;
    }

    public static bool EnforceAll(IReadOnlyList<IPolicy> policies, Request req)
    {
        var ok = true;
        foreach (var policy in policies)
        {
            if (policy.Allows(req)) continue;
            Console.WriteLine($"rejected by {policy.Name}");
            ok = false;
        }
        return ok;
    }

    public static void Main()
    {
        var req = new Request("/v1/scrape", 7, 4096);

        Console.WriteLine($"shared code:      {Enforce(new MaxBody(1024), req)}");
        Console.WriteLine($"specialized code: {Enforce(new TenantQuota(7, 2048), req)}");

        var chain = new List<IPolicy>
        {
            new MaxBody(8192),
            new BlockedPaths("/admin"),
            new TenantQuota(7, 2048),   // boxed on the way into the list
        };
        Console.WriteLine($"interface calls:  {EnforceAll(chain, req)}");
    }
}

That last comment is the C# equivalent of Box::new. Putting a struct into a List<IPolicy> boxes it, silently, and Rust makes you type the allocation out.

Writing Vec<dyn Policy> and being confused. Trait objects are unsized, so they cannot be stored by value. E0277 tells you the size cannot be known at compile time. You want Vec<Box<dyn Policy>>, or a slice of references.

Panicking at E0038 and redesigning the trait. Usually the fix is where Self: Sized on the one or two methods causing it, not a new hierarchy.

Making everything generic out of habit. In C# a spare type parameter is nearly free. In Rust it is a multiplier on codegen, it leaks into every signature downstream, and it makes the inference errors longer. If a function is only ever called with one type, take that type.

Expecting to find implementations at run time. A container scanning assemblies for IPolicy has no Rust translation, because there is no assembly to scan and the generic code that would have used those types was never emitted. You build the registry yourself, usually a Vec<Box<dyn Policy>> assembled in main, or you generate it with a macro.

What reflection gives C# that Rust cannot

Run-time type interrogation, first and most. if (policy is IDisposable d) is a normal thing to write in C#, and it works because the method table the object points at carries its full interface map. In Rust a &dyn Policy carries one vtable for one trait, and asking whether the value behind it also implements Serialize is not a question the language can answer. You get Any and downcast_ref, which recovers the one concrete type, and only for types that are 'static. If your design leans on interrogating objects, Rust will fight you the whole way.

Runtime reflection and generic instantiation are another difference. Rust has no built-in equivalent of constructing arbitrary closed generic types from Type objects. A Rust application can still select a registered deserializer by a name in configuration, or embed a JIT; those capabilities need an explicit design and libraries rather than standard reflection.

The CLR's ability to specialize code using the current process's profile is useful. Rust offers ahead-of-time specialization and optional PGO from previous runs, so the comparison is about deployment and optimization strategy, not whether Rust can use profiles at all.

Rust makes the choice between concrete generic types and trait objects visible in an API. That can help control allocation and dispatch on a hot path. You still need profiles and generated-code inspection to know what the optimizer produced; source-level abstractions alone do not predict tail latency.

Checking yourself

Why does #[no_mangle] do nothing on a generic function in Rust, and what does that tell you about typeof(T)? Because there is no single function to name, only one mangled symbol per instantiation. That same fact means Rust has no run-time T to hand you, while .NET keeps reified type arguments and can answer typeof(T) at run time.

where TPolicy : IPolicy in C# and P: Policy in Rust look identical. What happens differently at the call? In Rust the call is direct and inlinable in every instantiation. In C# it depends on the type argument: a value type gets specialized code and a direct call with no boxing, and a reference type runs the shared __Canon body where the call is a real interface dispatch, possibly devirtualized later by the JIT using profile data.

Your trait has one method with a generic parameter and you need a Vec of them. What is the smallest fix? Add where Self: Sized to that method. It becomes explicitly non-dispatchable, the trait is dyn compatible again, and every concrete implementor keeps the method.

When does the cost of dynamic dispatch actually show up in a profile? When the callee is small enough that the inlining you lost mattered more than the indirect call, and it runs often enough for that to accumulate. Inner loops of tight numeric or parsing code, not once-per-request policy checks.

Get the next deep dive by email

New deep dives on how production systems really behave, from Kubernetes networking to PostgreSQL internals. About one email a month.

You will get one email to confirm. Unsubscribe from any email with one click. Your address is used for this newsletter and nothing else.

Written by Zeeshan Adil

I run systems like this for a living. If your team is fighting the same problem, or wants this as a talk, write to me.