【发布时间】:2021-09-21 22:13:00
【问题描述】:
我想创建一个结构来实现具有默认关联类型和函数的特征以及专门的特征实现。但是,在尝试从默认实现构造结构实例时出现错误。
这是一些代码,显示了我正在尝试做的事情。在 Rust 操场上试一试here。
#![allow(incomplete_features)]
#![feature(specialization)]
pub trait Data {
type Data;
fn new() -> Self;
}
pub struct MyStruct<T> {
pub data: <Self as Data>::Data,
}
// default implementation
impl<T> Data for MyStruct<T> {
default type Data = u64;
default fn new() -> Self {
MyStruct::<T> {data: 1u64}
}
}
// a specialized implementation
impl Data for MyStruct<i64> {
type Data = u32;
fn new() -> Self {
MyStruct::<i64> {data: 1u32}
}
}
这给出了错误:
error[E0308]: mismatched types
--> src/lib.rs:16:30
|
14 | default type Data = u64;
| ------------------------ expected this associated type
15 | default fn new() -> Self {
16 | MyStruct::<T> {data: 1u64}
| ^^^^ expected associated type, found `u64`
|
= note: expected associated type `<MyStruct<T> as Data>::Data`
found type `u64`
For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error
错误描述非常笼统,我不确定自己做错了什么。我知道这是一个不完整的功能是有原因的,但我觉得我做错了什么,而不是这个功能有问题。
【问题讨论】:
-
我可以将此添加到问题中,但以下代码可以编译。然而,这只会让我更加困惑。 Rust playground
标签: rust