I'm trying to work on a math library that has constants and functions. What I need to do to bind a value to a trait that uses generics?
The functions in my Rust 1.30.0 project that employs generics as parameters and I need the constants to match the same type of T
so I can operate with them in a function (here I am also using the num crate):
use num_traits as ntraits; // 0.2.6
use std::{f32, f64};
pub trait consts<T> {
const INGA: T;
}
impl<T> consts<f32> for T {
const INGA: f32 = f32::consts::FRAC_2_SQRT_PI;
}
impl<T> consts<f64> for T {
const INGA: f64 = f64::consts::FRAC_2_SQRT_PI;
}
pub struct CMPS<T> {
pub a: T,
pub b: T,
}
pub type CMPS32 = CMPS<f32>;
pub type CMPS64 = CMPS<f64>;
impl<T: Clone + ntraits::Float + ntraits::FromPrimitive> CMPS<T> {
pub fn cerf(a: T, b: T) -> CMPS<T> {
let pr: T = consts::INGA;
let rtr = a;
let rti = b;
CMPS { a: rtr, b: rti }
}
}
But when I try to perform this binding, expecting pr
to be the same type as T
and match the value of INGA
as this:
let pr: T = consts::INGA;
It only outputs errors like:
error[E0283]: type annotations required: cannot resolve `_: consts<T>`
--> src/lib.rs:27:21
|
27 | let pr: T = consts::INGA;
| ^^^^^^^^^^^^
|
note: required by `consts::INGA`
--> src/lib.rs:5:5
|
5 | const INGA: T;
| ^^^^^^^^^^^^^^
I got it by adding + consts<T>
in the CMPS
implementation and changing let pr: T = consts::INGA;
to let pr = T::INGA
resulting in the following:
impl<T: Clone + ntraits::Float + ntraits::FromPrimitive + consts<T>> CMPS<T> {
pub fn cerf(a: T, b: T) -> CMPS<T> {
let pr = T::INGA;
CMPS { a: rtr, b: rti }
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.