Answer the question
In order to leave comments, you need to log in
How to cast template type T: Num to any other type that implements Num?
There is crate num .
It has the trait Num, which describes the properties of all numeric types in Rust (both primitive and not so).
In non-template code, I can afford to cast any numeric type to any other (I take responsibility for type narrowing). However, I can't find the same way for boilerplate code.
For example, I have a type T that implements Num. Most likely, it is obvious that it can be cast to any other type that implements Num (in any case, primitive types are definitely possible).
But the rasta compiler tells me that this is a non-trivial cast (non-trivial types are involved in it - T, even if it is a regular u32, T is still non-trivial, because all checks are carried out before instantiation, which infuriates, where are my pluses?) and what to use either Into or From (unfortunately, this is runtime).
Initially, the code was like this, and I expected that it would not compile:
pub fn foo<U>(bar: U) -> u8
where
U: Num,
{
bar as u8
}
error[E0605]: non-primitive cast: `U` as `u8`
--> src\map\chunk.rs:54:9
|
54 | bar as u8
| ^^^^^^^^^
|
= note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait
pub fn foo<U>(bar: U) -> u8
where
U: Num + Into<u8>,
{
bar.into()
}
fn main() {
let float = 0f32;
foo(float);
}
error[E0277]: the trait bound `u8: std::convert::From<f32>` is not satisfied
--> src\main.rs:45:5
|
36 | pub fn foo<U>(bar: U) -> u8
| ---
37 | where
38 | U: Num + Into<u8>,
| -------- required by this bound in `foo`
...
45 | foo(float);
| ^^^ the trait `std::convert::From<f32>` is not implemented for `u8`
|
= help: the following implementations were found:
<u8 as std::convert::From<bool>>
<u8 as std::convert::From<std::num::NonZeroU8>>
= note: required because of the requirements on the impl of `std::convert::Into<u8>` for `f32`
Answer the question
In order to leave comments, you need to log in
A strange desire, but here's a solution for you:
extern crate num;
use num::ToPrimitive;
pub fn foo<T>(bar: T) -> Option<u8> where T: ToPrimitive,
{
bar.to_u8()
}
fn main(){
println!("That's {}", foo(2.5f32).unwrap())
}
// That's 2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question