Aditya
Aditya

Reputation: 205

How to create a generic function that takes Range<T> as an argument?

So far I have written a simple code that doesn't do much. The compiler suggested me to add a trait bound Step. But after adding it the compiler gives me an error.

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!();
}

Error :

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

Upvotes: 1

Views: 840

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71035

You can workaround the Step trait being unstable by specifying that you want any type that Range is iterable with:

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

Upvotes: 3

Related Questions