不匹配的类型:预期的结构,找到关联的类型

nnn*_*mmm 3 rust

我定义了许多TryFrom实例,并想编写一个可以使用所有这些类型的函数。

use std::convert::TryFrom;

// several structs like this that are TryFrom<i32>
struct SuperiorThanZero(i32);

impl TryFrom<i32> for SuperiorThanZero {
    type Error = String;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        unimplemented!()
    }
}

fn from_three<T>() -> Result<T, String>
where
    T: TryFrom<i32>,
{
    T::try_from(3)
}
Run Code Online (Sandbox Code Playgroud)

这不会编译:

use std::convert::TryFrom;

// several structs like this that are TryFrom<i32>
struct SuperiorThanZero(i32);

impl TryFrom<i32> for SuperiorThanZero {
    type Error = String;

    fn try_from(value: i32) -> Result<Self, Self::Error> {
        unimplemented!()
    }
}

fn from_three<T>() -> Result<T, String>
where
    T: TryFrom<i32>,
{
    T::try_from(3)
}
Run Code Online (Sandbox Code Playgroud)

如果我将错误类型定义为&'static str,则消息将更改为Expected reference, found associated type

关于错误有多个问题Expected associated type, found struct [...],即associated type交换的具体类型,但它们似乎不相关。

nnn*_*mmm 6

罪魁祸首是特质束缚T: TryFrom<i32>。它没有指定错误是String

为此,您可以编写where T: TryFrom<i32, Error = String>.