hi,
I'm having trouble with type constraints.
In this example into() fails but casting with as works:
fn example() {
let a: u64 = 0;
let b: f64 = a.into(); // Error - From<u64> not satisifed
let c: f64 = a as f64; // Works
}
I have a generic function, but it's wrong because you can't cast to and from f64:
fn example_generic<T>(v: T) -> T
where
T: Into<f64>,
f64: Into<T>,
{
let x: f64 = v.into();
x.into()
}
Since as works, is it possible to add a type constraint to say "can cast with as"? Instead of Into<T>.
I also tried implementing Into with as for the number types, but you can't do that.
Sorry if this has been asked before.
giocri
September 9, 2026, 6:21am
2
as far as i know no, as is a special keyword without a trait behind it. in our project we worked around it by defining our own trait to convert between numeric types
it is possible to implement these casts as library, but it is not built into the language, nor provided by the standard library.
you can use NumCast from the num crate:
~~https://docs.rs/num/latest/num/trait.NumCast.html~~
EDIT:
actually, you may want to use AsPrimitive<f64>, which is the generic equivalence of cast with as f64:
A generic interface for casting between machine scalars with the `as` operator, which admits narrowing and precision loss. Implementers of this trait `AsPrimitive` should behave like a primitive numeric type (e.g. a newtype around another primitive),...
thank you @nerditation
here is a quick test using your solution:
fn example_generic<T>(v: T) -> T
where
T: AsPrimitive<f64>,
f64: AsPrimitive<T>,
{
let x: f64 = v.as_();
let y: T = x.as_();
y
}