【问题标题】:mismatched types: Expected struct, found associated type [duplicate]不匹配的类型:预期的结构,找到关联的类型 [重复]
【发布时间】: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>`

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

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    罪魁祸首是 trait bound T: TryFrom&lt;i32&gt;。它没有指定错误是String。

    为此,您可以写where T: TryFrom&lt;i32, Error = String&gt;。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-10
      • 2022-11-20
      • 1970-01-01
      • 2014-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-06
      相关资源
      最近更新 更多