【发布时间】:2022-08-03 20:39:43
【问题描述】:
我试图用一个类型特定的层来包装一个通用层,该层将值裁剪到一个范围内。我希望 2 层实现相同的 base_layer 特征,但包装层仅对 f32 类型有效。这在 Rust 中是否可行,或者我正在尝试做一些真正非惯用的 rust 面向对象的东西。
例子:
struct Layer<T> {
val: Vec<T>,
}
trait BaseLayer<T> {
fn get_mut(self: &Self, index: u32) -> Option<&mut T>;
}
impl<T> BaseLayer<T> for Layer<T> {
fn get_mut(self: &Self, index: u32) -> Option<&mut T> {
todo!()
}
}
struct Rangedf32Layer {
layer: Layer<f32>,
max: f32,
min: f32,
}
我想做类似的事情:
impl<T> BaseLayer<T> for Rangedf32Layer {
fn get_mut(self: &Self, index: u32) -> Option<&mut T> {
self.layer.get_mut(index).map(|v| {
*v = v.clamp(self.min, self.max);
v
})
}
}
但ofc得到:
mismatched types
expected enum `Option<&mut T>`
found enum `Option<&mut f32>`
并且更改输出类型会破坏 trait 实现。
-> Option<&mut f32>
给出:
method `get_mut` has an incompatible type for trait
我该怎么做呢?