error[E0562]: `impl Trait` is not allowed in cast expression types

error[E0562]: `impl Trait` is not allowed in closure return types

error[E0562]: `impl Trait` is not allowed in const types

error[E0562]: `impl Trait` is not allowed in static types

error[E0562]: `impl Trait` is not allowed in the type of variable bindings

impl 抽象化を未対応の箇所で使用した。

原因

impl 抽象化は関数の引数型と戻り値型でのみ使える。

それ以外、例えば変数バインドなどでの利用はまだ開発段階である。なお、過去には不安定な機能 impl_trait_in_bindings として実装されていたが、実装方法に問題があったらしく、現在その機能は削除されている。

サンプル


fn main() {
    let x = 1 as impl std::fmt::Display;
    println!("{x}");
}

error[E0562]: `impl Trait` is not allowed in cast expression types
 --> src\main.rs:2:18
  |
2 |     let x = 1 as impl std::fmt::Display;
  |                  ^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `impl Trait` is only allowed in arguments and return types of functions and methods

回避策

キャストや変数バインドについてはマクロが使える。


macro_rules! to_impl {
    ($x:expr, $t:ty) => {{
        fn f(x: $t) -> $t {x}
        f($x)
    }};
}

fn main() {
    let x = to_impl!(1, impl std::fmt::Display);
    println!("{x}");
}