Collect f32 range into a vector


#1

Hello. I often create test vectors with Range and collect like so:
let my_vec = (1…10).collect::<Vec>();
I find it more useful than just writing
let my_vec = vec![1,2,3,4,5,6,7,8,9];

Only recently I wanted to create a vector of floats and found out that collect does not do:
let my_vec = (1f32…10f32).collect::<Vec>();

Rust compiler already pointed out that there is no Range iterator method. Or at least, that is what I understood.

Is there a way to keep my syntax here, like, just importing something, or would you recommend something else (better in your opinion).

Thank you a lot
Fabrex


#2

A way to do it:

fn main() {
    let v: Vec<_> = (1u8 .. 10).map(f32::from).collect();
    println!("{:?}", v);
}

#3

That works out fine. But the method from is only implemented for i8, i16, u8 and u16. What if I need larger values?

An extra question I had, but forgot to mantion in the original post is:
How I could generate the intermediate values? Like [1.0, 1.5, 2.0, 2.5, …10.0]

Thank you in advance

leonardo

    March 2

A way to do it:

>     fn main() {
> let v: Vec<_> = (1u8 .. 10).map(f32::from).collect();
> println!("{:?}", v);
> }

#4

You might like itertools_num::linspace.


#5

Hehehe

Perfect.

Thanks


#6

Sorry. I thought that would be the solution. But I can’t seem to import the itertools_num crate.

I wrote my toml file with

[dependencies]
itertools="*"
itertools_num="*"

And used both crates with

extern crate itertools;
extern crate itertools_num;

use itertools_num::linspace;

When I typed cargo build, I got.

no matching package named itertools_num found


#7

Nevermind that. Found out that the actual dependency is name as itertools-num.

The extern crate is itertools_num.

Sorry

Sorry. I thought that would be the solution. But I can’t seem to import the itertools_num crate.

I wrote my toml file with

> [dependencies]
> itertools="*"
> itertools_num="*"

And used both crates with

> extern crate itertools;
> extern crate itertools_num;
> 
> use itertools_num::linspace;

I32 to vector of i32