How to create array with generic type but set number?

Example playground:

use num_traits::{Float};

struct Foo<T: Float> {
    data: [T;3]
}

impl <T: Float> Foo<T> {
    fn new() -> Self {
        //neither of these work:
        let data:[T;3] = [1.0;3];
        let data = [1.0T;3];
        
        Self {data}
    }
}

fn main() {
    let foo = Foo::new();
    println!("{:?}", foo.data);
}

You could use T::one() if you want to fill it with ones

1 Like

You can't use literals like 1.0 for generic types. Float requires One though, so you can write this array as [T::one(); 3]. For arbitrary numbers, you'll have to create that number of type T first, then you can copy it into an array the same way.

2 Likes

By this do you mean to create a new trait (say "Ten") and impl it/call it similar to T::one()?

Well, you could use NumCast if you want to make 10, and call it like T::from(10.0); Note that NumCast is required to implement Float, so all implementations of Float also implement NumCast

1 Like

Thanks for the help! Was going to fix my errors and head to bed but got stuck on one more thing:

Is it possible to go from a string to generic Float type?

I try foo.parse::<T>() but I get "std::str::FromStr is not implemented for T"

You could add the FromStr bound to T, but other than that you could parse to f64 and convert that to a T with NumCast

1 Like

The existing Float: Num also gets you from_str_radix(s: &str, radix: u32) -- try radix 10.

2 Likes

Thanks for the help y'all! Everything seems to be working now, goodnight! :slight_smile:

use num::One; // 0.2.0
use num_traits::Float;

struct Foo<T: Float> {
    data: [T;3]
}

impl <T: Float> Foo<T> {
    fn new() -> Foo<T> {
        let data = [One::one();3];
        Foo {data}
    }
}

fn main() {
    let foo = Foo::<Float>::new();
    println!("{:?}", foo.data);
}

Hi, folks. I did some modification following advices above, but something wrong.
I do not know how to fix it. Would you please share your soluction about this problem?

Error message:

   Compiling playground v0.0.1 (/playground)
error[E0038]: the trait `num_traits::float::Float` cannot be made into an object
  --> src/main.rs:16:21
   |
16 |     let foo = Foo::<Float>::new();
   |                     ^^^^^ the trait `num_traits::float::Float` cannot be made into an object
   |
   = note: the trait cannot use `Self` as a type parameter in the supertraits or where-clauses

error: aborting due to previous error

For more information about this error, try `rustc --explain E0038`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

You need to pick a concrete type to instantiate Foo with, for example Foo::<f64>::new()

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.