【问题标题】:How to create a generic function that takes Range<T> as an argument?如何创建一个以 Range<T> 作为参数的通用函数?
【发布时间】:2022-08-17 00:51:51
【问题描述】:

到目前为止,我已经编写了一个简单的代码,它并没有做太多的事情。 编译器建议我添加一个特征绑定步骤。但是在添加它之后,编译器给了我一个错误。

use std::fmt::Display;
use std::ops::Range;
use std::iter::Step;

fn main() {
    display(0..10);
}

fn display<T: Display + Step>(range: Range<T>) {
    for i in range {
        print!(\"{i} \");
    }
    println!();
}

错误 :

Compiling playground v0.0.1 (/playground)
error[E0658]: use of unstable library feature \'step_trait\': recently redesigned
 --> src/main.rs:3:5
  |
3 | use std::iter::Step;
  |     ^^^^^^^^^^^^^^^
  |
  = note: see issue #42168 <https://github.com/rust-lang/rust/issues/42168> for more information
  = help: add `#![feature(step_trait)]` to the crate attributes to enable

error[E0658]: use of unstable library feature \'step_trait\': recently redesigned
 --> src/main.rs:9:25
  |
9 | fn display<T: Display + Step>(range: Range<T>) {
  |                         ^^^^
  |
  = note: see issue #42168 <https://github.com/rust-lang/rust/issues/42168> for more information
  = help: add `#![feature(step_trait)]` to the crate attributes to enable

For more information about this error, try `rustc --explain E0658`.
error: could not compile `playground` due to 2 previous errors

    标签: rust


    【解决方案1】:

    您可以通过指定您想要 Range 可迭代的任何类型来解决 Step 特征不稳定的问题:

    fn display<T: Display>(range: Range<T>)
    where
        Range<T>: Iterator<Item = T>,
    {
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 2019-06-25
      相关资源
      最近更新 更多