27

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?

ljedrz
  • 20,316
  • 4
  • 69
  • 97
Timon Post
  • 2,779
  • 1
  • 17
  • 32

1 Answers1

47

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>
ljedrz
  • 20,316
  • 4
  • 69
  • 97