[英]Implement a generic trait but only for a specific type
我试图用一个类型特定的层来包装一个通用层,该层将值裁剪到一个范围内。 我希望 2 层实现相同的 base_layer 特征,但包装层仅对 f32 类型有效。 这在 Rust 中是否可行,或者我正在尝试做一些非常非惯用的 rust object 面向的东西。
例子:
struct Layer<T> {
val: Vec<T>,
}
trait BaseLayer<T> {
fn get_mut(self: &mut Self, index: u32) -> Option<&mut T>;
}
impl<T> BaseLayer<T> for Layer<T> {
fn get_mut(self: &mut Self, index: u32) -> Option<&mut T> {
self.val.get_mut(index as usize)
}
}
struct Rangedf32Layer {
layer: Layer<f32>,
max: f32,
min: f32,
}
我想做类似的事情:
impl<T> BaseLayer<T> for Rangedf32Layer {
fn get_mut(self: &mut 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>`
并且更改 output 类型会破坏特征实现。
-> Option<&mut f32>
给出:
method `get_mut` has an incompatible type for trait
我将如何 go 这样做?
相反,如果试图使您的impl
通用,则可以改为将 trait 传递给具体类型:
impl BaseLayer<f32> for Rangedf32Layer {
fn get_mut(self: &Self, index: u32) -> Option<&mut f32> {
self.layer.get_mut(index).map(|v| {
*v = v.clamp(self.min, self.max);
v
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.