Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why was the dyn syntax introduced? [duplicate]

In Rust 1.27.0 a new syntax is introduced - the dyn keyword was added.

  // old => new   Box<Foo> => Box<dyn Foo>   &Foo => &dyn Foo   &mut Foo => &mut dyn Foo 

What does it actually do and why was it added?

like image 359
Timon Post Avatar asked Jun 22 '18 11:06

Timon Post


People also ask

What does dyn do Rust?

The dyn keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be 'object safe'. Unlike generic parameters or impl Trait , the compiler does not know the concrete type that is being passed. That is, the type has been erased.

What is trait object?

A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of an object safe base trait plus any number of auto traits. Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.


1 Answers

This helps differentiate between traits/trait objects and structs; &Foo, Box<Foo> and impl Bar for Foo were ambiguous, because in all of them Foo could have been a trait or a struct.

With the addition of dyn this is no longer ambiguous, as traits are distinguished by the dyn keyword:

// trait objects (new dyn syntax) &Foo     => &dyn Foo &mut Foo => &mut dyn Foo Box<Foo> => Box<dyn Foo>  // structs (no change) &Bar &mut Bar Box<Bar> 
like image 170
ljedrz Avatar answered Oct 11 '22 22:10

ljedrz