【发布时间】:2022-10-04 23:57:04
【问题描述】:
尝试编写在 f32 和 f64 上通用的结构/实现。
我使用 trait num_traits::float::Float 作为 trait bound。
但是当函数中使用具体值时会出现编译器错误,例如初始化数组或使用数组的长度(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
}
}
【问题讨论】: