[英]How to select a constant according to a generic in Rust?
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):我的 Rust 1.30.0 项目中的函数使用泛型作为参数,我需要常量来匹配相同类型的
T
以便我可以在函数中使用它们(这里我也使用了 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:但是当我尝试执行此绑定时,期望
pr
与T
类型相同,并且匹配INGA
的值,如下所示:
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;
我通过在
CMPS
实现中添加+ consts<T>
并更改let pr: T = consts::INGA;
to let pr = T::INGA
resulting in the following: let pr = T::INGA
产生以下结果:
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 }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.