【问题标题】:Implement a generic trait but only for a specific type实现通用特征,但仅适用于特定类型
【发布时间】: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

我该怎么做呢?

    标签: generics rust traits


    【解决方案1】:

    相反,如果试图使您的 impl 泛型,您可以改为将特征传递给具体类型:

    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
            })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-08
      • 2017-06-20
      • 2020-09-04
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 2021-12-28
      相关资源
      最近更新 更多