为什么 Rust 不能推断 Iterator::sum 的结果类型? [英] Why can't Rust infer the resulting type of Iterator::sum?

查看:32
本文介绍了为什么 Rust 不能推断 Iterator::sum 的结果类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有效:

fn main() {
    let a: i32 = (1i32..10).sum();
    let b = a.pow(2);
}

如果我从 a 中删除了 i32 类型,则会出现此错误:

If I remove the i32 type from a, then I get this error:

rustc 1.13.0 (2c6933acc 2016-11-07)
error: the type of this value must be known in this context
 --> <anon>:3:13
  |
5 |     let b = a.pow(2);
  |             ^^^^^^^^

运行示例

我本来希望 Rust 将 (1i32..10) 变成一个 i32 迭代器,然后 sum() 知道返回一个i32.我错过了什么?

I would have expected that Rust turns (1i32..10) into an i32 iterator and then sum() knows to return an i32. What am I missing?

推荐答案

sum的定义方式,返回值是开放式的;不止一种类型可以实现特征Sum.这是一个示例,其中使用了 a 的不同类型,这两种类型都可以编译:

The way sum is defined, the return value is open-ended; more than one type can implement the trait Sum<i32>. Here's an example where different types for a are used, both of which compile:

#[derive(Clone, Copy)]
struct Summer {
    s: isize,
}

impl Summer {
    fn pow(&self, p: isize) {
        println!("pow({})", p);
    }
}

impl std::iter::Sum<i32> for Summer {
    fn sum<I>(iter: I) -> Self
    where
        I: Iterator<Item = i32>,
    {
        let mut result = 0isize;
        for v in iter {
            result += v as isize;
        }
        Summer { s: result }
    }
}

fn main() {
    let a1: i32 = (1i32..10).sum();
    let a2: Summer = (1i32..10).sum();
    let b1 = a1.pow(2);
    let b2 = a2.pow(2);
}

游乐场

因为这两种结果类型都是可能的,所以不能推断类型,必须明确指定,要么通过 turbofish (sum::<X>()) 或作为表达式的结果(let x: X = ...sum();).

Since both result types are possible, the type cannot be inferred and must be explicitly specified, either by a turbofish (sum::<X>()) or as the result of the expression (let x: X = ...sum();).

这篇关于为什么 Rust 不能推断 Iterator::sum 的结果类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆