[英]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.