HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

What does "dyn" mean in a type?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
dynwhatdoesmeantype

Problem

I have recently seen code using the dyn keyword:

fn foo(arg: &dyn Display) {}

fn bar() -> Box {}


What does this syntax mean?

Solution

TL;DR: It's a syntax for specifying the type of a trait object and must be specified for clarity reasons.

Since Rust 1.0, traits have led a double life. Once a trait has been declared, it can be used either as a trait or as a type:
// As a trait
impl MyTrait for SomeType {}

// As a type!
impl MyTrait {}
impl AnotherTrait for MyTrait {}


As you can imagine, this double meaning can cause some confusion. Additionally, since the MyTrait type is an unsized / dynamically-sized type, this can expose people to very complex error messages.

To ameliorate this problem, RFC 2113 introduced the dyn syntax. This syntax is available starting in Rust 1.27:
use std::{fmt::Display, sync::Arc};

fn main() {
let display_ref: &dyn Display = &42;
let display_box: Box = Box::new(42);
let display_arc: Arc = Arc::new(42);
}


This new keyword parallels the impl Trait syntax and strives to make the type of a trait object more obviously distinct from the "bare" trait syntax.

dyn is short for "dynamic" and refers to the fact that trait objects perform dynamic dispatch. This means that the decision of exactly which function is called will occur at program run time. Contrast this to static dispatch which uses the impl Trait syntax.

The syntax without dyn is now deprecated and was removed in the 2021 edition.

  • Why would I implement methods on a trait instead of as part of the trait?



  • What makes something a "trait object"?

Context

Stack Overflow Q#50650070, score: 100

Revisions (0)

No revisions yet.