Why was the dyn syntax introduced?

Timon Post picture Timon Post · Jun 22, 2018 · Viewed 8.1k times · Source

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?

Answer

ljedrz picture ljedrz · Jun 22, 2018

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>