简体   繁体   English

实现通用特征,但仅适用于特定类型

[英]Implement a generic trait but only for a specific type

I'm trying to wrap a generic layer with a type specific layer that crops values to a range.我试图用一个类型特定的层来包装一个通用层,该层将值裁剪到一个范围内。 I want the 2 layers to implement the same base_layer trait but the wrapping layer would only be valid for the f32 type.我希望 2 层实现相同的 base_layer 特征,但包装层仅对 f32 类型有效。 Is this possible in Rust or I'm I trying to do something really non-idiomatic rust object oriented stuff.这在 Rust 中是否可行,或者我正在尝试做一些非常非惯用的 rust object 面向的东西。

Example:例子:

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

And I want to do something like:我想做类似的事情:

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

but ofc get:但ofc得到:

mismatched types
expected enum `Option<&mut T>`
   found enum `Option<&mut f32>`

And changing the output type would break the trait implementation.并且更改 output 类型会破坏特征实现。

 -> Option<&mut f32>

Gives:给出:

method `get_mut` has an incompatible type for trait

How would I go about doing this?我将如何 go 这样做?

Instead if trying to make your impl generic, you can instead pass the trait a concrete type:相反,如果试图使您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM