Error [E0433] when `dyn` used with absolute path
Asked Answered
O

1

6

I was playing with a dyn traits introduced in Rust 1.27 and stumbled into this compiler error:

error[E0433]: failed to resolve. Use of undeclared type or module `dyn`
 --> src\main.rs:1:30
  |
1 | fn _run0() -> Result<(), Box<dyn ::std::error::Error>> { Ok(()) }
  |                              ^^^ Use of undeclared type or module `dyn`

All other variants compile fine:

fn _run0() -> Result<(), Box<dyn ::std::error::Error>> { Ok(()) } // Error

fn _run1() -> Result<(), Box<dyn std::error::Error>> { Ok(()) } // Ok

fn _run2() -> Result<(), Box<::std::error::Error>> { Ok(()) } // Ok

Is it intended behavior?


rustc 1.27.0 (3eda71b00 2018-06-19)

Occultation answered 27/6, 2018 at 21:51 Comment(1)
This is currently reproducible in the playground as well!Mame
P
10

This is a backwards compatibility "gotcha" of the fact that dyn is a contextual keyword. Before the new syntax was added, you can write this code which uses dyn as a module name:

mod dyn {
    pub trait Error {}
}

fn example() -> Box<dyn ::Error> {
//                     ^ space doesn't matter
    unimplemented!()
}

This cannot stop compiling, so it must be parsed as a path component.

You can add parenthesis to be explicit:

fn example() -> Box<dyn (::dyn::Error)> { /* ... */ }

In the 2018 edition, you can use crate at the beginning of a path:

fn example() -> Box<dyn crate::dyn::Error> { /* ... */ }
Pampuch answered 27/6, 2018 at 22:0 Comment(5)
@Tim not as of the current 2018 implementation. Seems deliberate.Pampuch
The way I see it, a safe "fix" for this would involve deprecating dyn as a module name in one edition and prohibiting it in the next one. That might take a while.Mame
@Mame Since 2018 is a preview at the moment, I don't see, why this shouldn't be possible for 2018.Croup
On the other hand... that would lead to inconsistency with Path Clarity. The :: should no longer be required at all.Croup
@Tim Rust code in one edition must compile and have the same behaviour in the next. So no, we would need at least two editions for such a change to happen.Mame

© 2022 - 2024 — McMap. All rights reserved.