Rust 如何从默认方法返回可专门化的关联类型?

Rust 如何从默认方法返回可专门化的关联类型?,rust,specialization,Rust,Specialization,我赞成生锈。它需要转换 ((A,B), (C, (D, E)), F) 进入 我尝试使用专门化,但编译器不喜欢: /// For non-tuple types. impl<T> IntoCons for Val<T> { default type Out = Cons<T, Nil>; default fn into_cons(self) -> Cons<T, Nil> { Cons {

我赞成生锈。它需要转换

((A,B), (C, (D, E)), F)
进入

我尝试使用专门化,但编译器不喜欢:

/// For non-tuple types.
impl<T> IntoCons for Val<T> {
    default type Out = Cons<T, Nil>;

    default fn into_cons(self) -> Cons<T, Nil> {
        Cons {
            head: self,
            tail: Nil,
        }
    }
}

编译器输出:

错误[E0308]:类型不匹配
-->src/main.rs:17:9
|
16 |默认fn it(self)->self::it{
|----------应为“”::由于返回类型,它为“”
17 |         0
|^应为关联类型,找到整型变量
|
=注意:应为类型“”::它`
找到类型`{integer}`

这里的问题是,您返回的是
Self::It
,但给它一个0。如果有人用
It
作为
String
来实现它,会发生什么?因为无法证明这总是一个数字,所以您需要一个特征绑定或更改方法签名

一种可能的方法是:

pub trait Tr {
    type It: Default;
    fn it(self) -> Self::It;
}

impl<T> Tr for T
where
    T: Debug,
{
    default type It = u8;

    default fn it(self) -> Self::It {
        Default::default()
    }
}
pub-trait-Tr{
键入:默认值;
fn it(self)->self::it;
}
T的impl Tr
哪里
T:调试,
{
默认类型It=u8;
默认fn-it(self)->self::it{
Default::Default()
}
}

如果有人用
String
来实现它,会发生什么呢?这不是trait中的实现,而是一个全面的实现。如果你这样做,那么代码就可以工作了。是什么让专门化实现不同于常规实现?因为在这种情况下,它是一种具体类型。你只需要
默认类型It=u8;
以供编译。由于使用默认trait绑定,该实现始终有效。请参见此处:我不想返回可以从default::default()中删除的简单内容但我接受了这个答案,因为我的示例是错误的,我将使用oibits来解决这个问题。我不想使用oibits,因为它看起来永远不稳定,但它是有效的,我希望专门化特性能够改善这种情况
#![feature(specialization)]
use std::fmt::{Debug, Display};

pub trait Tr {
    type It;
    fn it(self) -> Self::It;
}

impl<T> Tr for T
where
    T: Debug,
{
    default type It = u8;

    default fn it(self) -> Self::It {
        0
    }
}

impl<T> Tr for T
where
    T: Debug + Display,
{
    type It = u16;

    fn it(self) -> Self::It {
        0
    }
}

fn main() {}
pub trait Tr {
    type It: Default;
    fn it(self) -> Self::It;
}

impl<T> Tr for T
where
    T: Debug,
{
    default type It = u8;

    default fn it(self) -> Self::It {
        Default::default()
    }
}