【发布时间】:2019-09-17 18:57:44
【问题描述】:
我定义了许多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)
}
这不会编译:
error[E0308]: mismatched types
--> src/lib.rs:16:9
|
12 | fn from_three<T>() -> Result<T, String>
| ----------------- expected `std::result::Result<T, std::string::String>` because of return type
...
16 | T::try_from(3)
| ^^^^^^^^^^^^^^ expected struct `std::string::String`, found associated type
|
= note: expected type `std::result::Result<_, std::string::String>`
found type `std::result::Result<_, <T as std::convert::TryFrom<i32>>::Error>`
如果我将错误类型定义为&'static str,则消息将更改为Expected reference, found associated type。
关于错误Expected associated type, found struct [...] 有多个问题,即associated type 和具体类型已交换,但它们似乎不相关。
【问题讨论】:
标签: rust