如何指定特征界限或逻辑

发布于 2025-02-05 03:47:00 字数 463 浏览 1 评论 0原文

我希望以一般方式以RUST的形式实现2D矩阵功能,其中矩阵的元素将是数字(i32,i64,u32,u32,u64,f32,f64)。通用类型看起来如下所示:

#[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(){
        ...
    }
}

我知道您可以特征与 + 符号以“ ”的形式,其中t:bound1 + bound2 ”。有没有一种方法可以干净地特征界限在一起?

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). 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". Is there a way to cleanly OR trait bounds together?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

素染倾城色 2025-02-12 03:47:00

不,但这通常不是您想要的。您可以通过声明标签性状来做到这一点,例如:

pub trait NumberTrait {}

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

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

通常您实际上试图完成的工作是强制执行t支持某些操作,例如加法和乘法。如果是这样,只需绑定这些操作:

use std::ops::*;

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

这将涵盖所有原始数字类型,但 也涵盖了定义这些操作的其他类型,例如第三方“十进制”或“大数字”(例如128/256/512位整数)类型。

No, but this isn't usually what you want anyway. You can do this by declaring a tag trait, like:

pub trait NumberTrait {}

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

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

However, usually what you're actually trying to accomplish is enforcing that T supports some set of operations like addition and multiplication. 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" (e.g. 128/256/512-bit integers) types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文