嘗試撰寫在 f32 和 f64 上通用的結構/實作。
我使用特征num_traits::float::Float作為特征界限。
但是當函式中使用具體值時會出現編譯器錯誤,例如初始化陣列或使用陣列的長度(usize)時。想將具體型別轉換為泛型 T,還是什么?我該如何處理?
示例 1:
pub struct RingArray<T: Float, const N: usize> {
tail: usize, // Index of the most recently added element
data: [T; N], // Array containing the data.
}
impl<T: Float, const N: usize> RingArray<T, N> {
/// Creates a new RingArray of with length `length` and initialized to `init_value`.
pub fn new() -> Self {
Self {
tail: N - 1, // raw index to the last element
// Initialize the data array to 0.0
data: [0.0; N], // <-- ERROR. Compiler complains here about 0.0. Expected type T found {float}
}
}
}
示例 2:
pub struct MovingAverageFilter<T: Float, const N: usize> {
ring_array: RingArray<T, N>,
sum: T,
}
impl <T: Float, const N: usize> MovingAverageFilter<T, N> {
pub fn push(&mut self, input: T) -> T {
// Push the input and pop the head.
let head = self.ring_array.push(input);
// Add input to the sum and subtract the head
self.sum = self.sum input - head;
let length = self.ring_array.len();
// Want to cast length to type T. How?
self.sum/length // <-- ERROR. Expectded denom to be type T, found usize
}
}
uj5u.com熱心網友回復:
0.0是不能在通用背景關系中使用的文字。相反,您可以使用Zerofrom num_traits,這是具有有意義的“零”值的型別的特征:
use num_traits::Zero;
pub fn new() -> Self {
Self {
tail: N - 1,
// Initialize the data array to 0.0
data: [Zero::zero(); N],
}
}
對于第二部分,您嘗試將通用數字型別除以usize. 您需要usize先將 轉換為浮點型別,您可以通過FromPrimitive從同一個板條箱中限制型別來做到這一點:
use num_traits::FromPrimitive;
impl <T: Float FromPrimitive, const N: usize> MovingAverageFilter<T, N> {
pub fn push(&mut self, input: T) -> T {
// Push the input and pop the head.
let head = self.ring_array.push(input);
// Add input to the sum and subtract the head
self.sum = self.sum input - T::from_usize(head).unwrap();
let length = self.ring_array.len();
// Convert the usize to a T before dividing
self.sum / T::from_usize(length).unwrap()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511218.html
標籤:仿制药锈
上一篇:有沒有辦法用泛型型別編譯?
