如何指定特征界限或逻辑
我希望以一般方式以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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,但这通常不是您想要的。您可以通过声明标签性状来做到这一点,例如:
通常您实际上试图完成的工作是强制执行
t
支持某些操作,例如加法和乘法。如果是这样,只需绑定这些操作:这将涵盖所有原始数字类型,但 也涵盖了定义这些操作的其他类型,例如第三方“十进制”或“大数字”(例如128/256/512位整数)类型。
No, but this isn't usually what you want anyway. You can do this by declaring a tag trait, like:
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: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.