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 抽象化を未対応の箇所で使用した。
let 束縛
let 束縛の型に impl 抽象化を使用したパターン。
fn main() {
let x: impl std::fmt::Display = 1;
println!("{x}");
}
error[E0562]: `impl Trait` is not allowed in the type of variable bindings --> src\main.rs:2:12 | 2 | let x: impl std::fmt::Display = 1; | ^^^^^^^^^^^^^^^^^^^^^^ | = note: `impl Trait` is only allowed in arguments and return types of functions and methods = note: see issue #63065 <https://github.com/rust-lang/rust/issues/63065> for more information = help: add `#![feature(impl_trait_in_bindings)]` to the crate attributes to enable = note: this compiler was built on 2026-07-18; consider upgrading it if it is out of date
エラーメッセージにある通り、はまだナイトリー限定だが、
不安定な機能 impl_trait_in_bindings を有効化すると解決される。
マクロを使うと安定板でも対策できる。
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}");
}
let 束縛以外で impl 抽象化を使用したパターン。
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}");
}