繁体   English   中英

无法创建使用文字零的泛型函数

[英]Cannot create a generic function that uses a literal zero

我试图编写一个与内置Range相似的Rust函数,但是我想要只返回X个数字并将其作为列表返回的东西,这就是为什么我要创建此函数的原因:extern crate num;

use num::Integer;

fn positions<T: Integer>(start: T, step: T, len: T) -> Vec<T> {
    (0..len).map(|i| start + step * i).collect()
}

fn main() {
    println!("{:?}", positions(10, 2, 10));
}

除了我遇到编译器错误:

error[E0308]: mismatched types
 --> src/main.rs:6:9
  |
6 |     (0..len).map(|i| start + step * i).collect()
  |         ^^^ expected integral variable, found type parameter
  |
  = note: expected type `{integer}`
             found type `T`
  = help: here are some functions which might fulfill your needs:
          - .div_floor(...)
          - .gcd(...)
          - .lcm(...)
          - .mod_floor(...)

error[E0308]: mismatched types
 --> src/main.rs:6:37
  |
6 |     (0..len).map(|i| start + step * i).collect()
  |                                     ^ expected type parameter, found integral variable
  |
  = note: expected type `T`
             found type `{integer}`

问题是0 我目前尚不清楚确切的规则,但让我们大致概括一下: 0是某些特定的整数类型,它与T可能相同也可能不同。 因此,编译器无法计算出要设定range的类型参数。

您可以使用Zero::zero解决此问题:

fn positions<T: Integer>(start: T, step: T, len: T) -> Vec<T> {
    (T::zero()..len).map(|i| start + step * i).collect()
}

这为编译器提供了足够的空间来推断range的两个参数是同一类型。 但是,这还不足以将Range用作迭代器:

error: no method named `map` found for type `std::ops::Range<T>` in the current scope
 --> src/main.rs:8:22
  |
8 |     (T::zero()..len).map(|i| start + step * i).collect()
  |                      ^^^
  |
  = note: the method `map` exists but the following trait bounds were not satisfied: `T : std::iter::Step`, `&'a T : std::ops::Add`, `std::ops::Range<T> : std::iter::Iterator`

不幸的是,从Rust 1.17开始, Step trait是不稳定的,因此,目前没有使用稳定的Rust解决此问题的好方法。

使用不稳定的Rust,您可能需要实现以下Step

#![feature(step_trait)]

extern crate num;

use num::Integer;

fn positions<T>(start: T, step: T, len: T) -> Vec<T>
    where T: Integer + std::iter::Step + Copy,
          for<'a> &'a T: std::ops::Add<Output = T>
{
    (T::zero()..len).map(|i| start + step * i).collect()
}

fn main() {
    println!("{:?}", positions(10, 2, 10));
}

需要要求可以复制(或克隆,如果愿意的话) T ,因为AddMul的实现按值消耗操作数,这意味着start + step * i只能被调用一次,除非它需要被多次调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM