我定义了许多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交换的具体类型,但它们似乎不相关。