[Beginner] Convert to generic type (number) from vec with number

Hi, I have some trouble with creating a generic code. I want to create a method from_vec.

    fn from_vec<T>(vec: Vec<T>) -> DataFrame  where T: NumCast {
            for value in vec.iter() {
                elements.push(Element::from(num::cast(*value).unwrap()));

At the moment value cannot be convertet to T. I have issue with

error[E0283]: type annotations required: cannot resolve `element::Element: std::convert::From<_>`
   --> src/dataframe.rs:218:31
|
218 |                 elements.push(Element::from(num::cast(*value).unwrap()));
|                               ^^^^^^^^^^^^^
|
= note: required by `std::convert::From::from`

Or without cast
the trait std::convert::From<T> is not implemented for element::Element
Here is my Element
The problem shows too if I tried to implement NumCast and ToPrimitive but always is the same error the traitnum_traits::cast::NumCastis not implemented forT``. I will be glad to some help.

You can cast T to any integer (NumCast) and you can go from a specific integer, (i32 it seems) to an Element. In such cases, Rust is currently unable to "guess the hole" when two generic functions are chained, even if there is only one type to fill the "hole" (i32).

So you need to be explicit about the transformation "path" and tell Rust to use i32 as the intermediary step. So, instead of:

Element::from(num::cast(*value).unwrap())

try doing:

Element::from(num::cast::<_, i32>(*value).unwrap())

other option is to bind T by T : ToPrimitive and call value.to_i32().unwrap(). This way the code is more readable and more versatile (NumCast is a subtrait of ToPrimitive).

2 Likes

@Yandros Thank you. What should I add when I want to add casting from f32? Some match with few number types and inside cast to current type? Of course I need to change specification of generic type.

I don't know, maybe you could try to cast to an intermediate f64 and from there try to go to a i32 if the f64 is an integer or else to a f32.

I don't know much about floating-point types, so I can't really tell you what the best strategy for this kind of situation could be (cc @TomP).

1 Like