简体   繁体   English

如何使用 OR 逻辑指定特征边界

[英]How can I specify trait bounds with OR logic

I am looking to implement 2D matrix functionality in Rust in a generic fashion where the elements of the matrix would be numerics (either i32, i64, u32, u64, f32, f64).我希望以通用方式在 Rust 中实现 2D 矩阵功能,其中矩阵的元素将是数字(i32、i64、u32、u64、f32、f64)。 The generic type would look something like shown below:泛型类型如下所示:

#[derive(Debug)]
pub struct Mat<T> {
    data: Vec<T>,
    shape: (usize, usize),
}

impl<T> Mat<T> where T: i32 OR i64 OR u32 OR u64 OR f32 OR f64{
    pub fn new(){
        ...
    }
}

I know that you can AND trait bounds with the + symbol in the form of " where T: bound1 + bound2 ".我知道您可以使用+符号以“ where T: bound1 + bound2 ”的形式对特征边界进行AND操作。 Is there a way to cleanly OR trait bounds together?有没有办法干净地特征界限在一起?

No, but this isn't usually what you want anyway.不,但这通常不是你想要的。 You can do this by declaring a tag trait, like:您可以通过声明标签特征来做到这一点,例如:

pub trait NumberType {}

impl NumberTrait for i32 {}
impl NumberTrait for i64 {}
// and so on...

impl<T> Mat<T> where T: NumberType { ... }

However, usually what you're actually trying to accomplish is enforcing that T supports some set of operations like addition and multiplication.但是,通常您实际上想要完成的是强制T支持某些操作,例如加法和乘法。 If so, just bound on those operations:如果是这样,只需绑定这些操作:

use std::ops::*;

impl<T> Mat<T> where T: Add<T, Output=T> + Mul<T, Output=T> { ... }

This will cover all of the primitive numeric types, but will also cover other types for which those operations are defined, such as third-party "decimal" or "big number" (eg 128/256/512-bit integers) types.这将涵盖所有原始数字类型,但将涵盖定义了这些操作的其他类型,例如第三方“十进制”或“大数”(例如 128/256/512 位整数)类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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