I am trying to implement a constant value of generic type, but the compiler can't figure out the type (Error: cannot find type T
in this scope).
use num::Float
pub const R: T = T::from(8314.4621).unwrap();
fn main() {
println!("{:?}", foo(3.0_f64))
}
pub fn foo<T: Float>(a: T) -> T {
a * R
}
- How should I declare the implemented traits for
T
like theFloat
trait of thenum
crate? - Furthermore, is there any easier way to declare the value instead of this verbose way
T::from(8314.4621).unwrap()
? - Just to be sure, is this solved in compile or run time?
CodePudding user response:
You cannot have a generic const
. You have to perform the calculation inside foo()
:
pub fn foo<T: Float>(a: T) -> T {
a * T::from(8314.4621).unwrap()
}
- Furthermore, is there any easier way to declare the value instead of this verbose way
T::from(8314.4621).unwrap()
?
Not for arbitrary numbers (for special numbers, e.g. 0
, -0
, 1
, ∞, etc. you can use the methods of the Float
trait and supertraits, e.g. zero()
).
- Just to be sure, is this solved in compile or run time?
For const
(which you can't), at compile time.
If inlined, at runtime, but the compiler will optimize it away.