【问题标题】:expected i32, found type parameter, but type parameter is i32 [duplicate]预期 i32,找到类型参数,但类型参数是 i32 [重复]
【发布时间】:2017-09-13 10:28:55
【问题描述】:
pub struct Table<T> {
    table: Vec<Vec<T>>
}

impl<i32> Display for Table<i32>
    where i32: Display
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (index, line) in self.table.iter().enumerate() {
            write!(f, "{}:\t", index+1);

            let mut sum = 0i32;
            for task in line {
                write!(f, "{} ", task);
                sum += *task;
            }

            write!(f, " : {}\n", sum);
        }

        Result::Ok(())
    }
}

此代码会导致令人困惑的错误消息:

error[E0308]: mismatched types
  --> src/table.rs:48:24
   |
48 |                 sum += *task;
   |                        ^^^^^ expected i32, found type parameter
   |
   = note: expected type `i32` (i32)
   = note:    found type `i32` (type parameter)

我不知道该怎么办。

【问题讨论】:

    标签: rust


    【解决方案1】:

    您不小心引入了一个名为 i32 的类型参数(而不是通常的 T)。我同意你的看法,编译器诊断可能会更好。

    在尖括号中impl之后添加一些东西,就像这样:

    impl<i32> Display for Table<i32>
    

    ... 总是会引入一个新的类型参数,就像 e.g. impl&lt;T&gt;。要解决您的问题,只需从 impl 关键字中删除此类型参数声明:

    impl Display for Table<i32> { ... }
    

    请注意,我还删除了不再有意义的 where 绑定。您不能将边界应用于具体类型。


    相关:

    【讨论】:

    • 成功了!谢谢!
    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 1970-01-01
    • 2014-11-20
    • 2020-10-13
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多