简体   繁体   English

如何在锈中声明可比较材料的通用矢量

[英]How to declare a generic vector of comparable stuffs in rust

How can I define a vector of comparable in Rust? 如何在Rust中定义可比向量?

Say, i32 , i16 ... 说, i32i16 ...

I tried arr: Vec<Ord> but the compiler complains about the trait "std::cmp::Ord" cannot be made into an object 我尝试了arr: Vec<Ord>但是编译器抱怨the trait "std::cmp::Ord" cannot be made into an object

Basically I need to store a vector of a vector of comparable objects. 基本上,我需要存储可比较对象向量的向量。 eg 例如

    struct Setup<T: Ord + Copy> {
        arr: Vec<Vec<T>>
    }

    impl<T: Ord + Copy> Setup<T> {
        fn new() -> Self {
            Self {
                arr: vec![
                    vec![1, 2, 3, 4, 5],
                    vec![1.0, 2.0, 3.0]
                ]
            }
        }
    }

Instead of letting the consumer decide what exactly the type is, I would like they can get a vector of comparable stuffs. 我希望他们可以得到类似产品的向量,而不是让消费者决定类型是什么。

The type Vec<Ord> would be a Vec where each item is a trait object. Vec<Ord>类型将是Vec ,其中每个项目都是一个特征对象。 What you'd want to do is do Vec<T> and then set the trait bound on T to be : Ord , eg 您要做的是执行Vec<T> ,然后将T上绑定的特征设置为: Ord ,例如

struct Foo<T: Ord> {
  arr: Vec<T>,
}

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

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