error[E0573]: expected type, found constant 'XXX'
error[E0573]: expected type, found variant 'Xxx'
型が要求される箇所に別のものを使用した。
エラー番号は違うが E0782 も同じ類いのエラーである。
通常型に他の何かを指定したパターン。
以下では、型に列挙型 Option の変異形 Some を指定している。
use std::fmt::Display;
fn main() {
show_default::<Some>();
}
fn show_default<T>()
where
T: Default + Display
{
println!("{}", T::default())
}
error[E0573]: expected type, found variant `Some` --> src\main.rs:4:20 | 4 | show_default::<Some>(); | ^^^^ not a type | help: try using the variant's enum | 4 - show_default::<Some>(); 4 + show_default::<core::option::Option>(); | 4 - show_default::<Some>(); 4 + show_default::<std::option::Option>(); |
定数型に定数値を指定したパターン。
以下では、ts::LEN が定数値として読まれている。
fn main() {
let arr = MyArray::<i32, ts::LEN>::default();
assert_eq!(arr.0.len(), 32);
}
struct MyArray<T, const N: usize>([T; N]);
impl<T: Default, const N: usize> Default for MyArray<T, N> {
fn default() -> Self {
Self(std::array::from_fn(|_| Default::default()))
}
}
mod ts {
pub const LEN: usize = 32;
}
error[E0573]: expected type, found constant `ts::LEN` --> src\main.rs:2:30 | 2 | let arr = MyArray::<i32, ts::LEN>::default(); | ^^^^^^^ not a type
値として解釈される原因はパス式にある。そのため、use で回避できる。
fn main() {
use ts::LEN;
let arr = MyArray::<i32, LEN>::default();
assert_eq!(arr.0.len(), 32);
}
struct MyArray<T, const N: usize>([T; N]);
impl<T: Default, const N: usize> Default for MyArray<T, N> {
fn default() -> Self {
Self(std::array::from_fn(|_| Default::default()))
}
}
mod ts {
pub const LEN: usize = 32;
}
中括弧で囲むと定数値を定数型として表現できる。
fn main() {
let arr = MyArray::<i32, { ts::LEN }>::default();
assert_eq!(arr.0.len(), 32);
}
struct MyArray<T, const N: usize>([T; N]);
impl<T: Default, const N: usize> Default for MyArray<T, N> {
fn default() -> Self {
Self(std::array::from_fn(|_| Default::default()))
}
}
mod ts {
pub const LEN: usize = 32;
}