是否有可能实现 Eq 类型的异构向量? [英] Is it possible to have a heterogeneous vector of types that implement Eq?

查看:28
本文介绍了是否有可能实现 Eq 类型的异构向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个包含诸如 Eq 之类特征的元素的向量,并且我需要异构向量.例如:

I want a vector for elements that contain a trait such as Eq and I need heterogeneous vectors. For example:

let mut x: Vec<Eq> = Vec::new();

x.push(1);
x.push("hello")

我收到一条错误消息,指出不能将 Eq 变成一个对象:

I get an error message that says that Eq cannot be made into an object:

error[E0038]: the trait `std::cmp::Eq` cannot be made into an object
 --> src/main.rs:2:20
  |
2 |     let mut x: Vec<Eq> = Vec::new();
  |                    ^^ the trait `std::cmp::Eq` cannot be made into an object
  |
  = note: the trait cannot use `Self` as a type parameter in the supertrait listing

是否有可能有一个指向我可以比较的事物的指针列表,而不管它们的类型?

Is it possible to have a list of pointers to things I can compare regardless of their types?

推荐答案

是否有可能有一个指向我可以比较的事物的指针列表,而不管它们的类型?

Is it possible to have a list of pointers to things I can compare regardless of their types?

这没有意义.你如何比较"一个 String 和一个 File 或者一个 Socket 和一个 GuiWindowFontFamily?

This doesn't make sense. How do you "compare" a String and a File or a Socket and a GuiWindowFontFamily?

该代码也有一些小问题,即它缺少任何类型的 trait 的间接性.请参阅什么是最佳创建方式对象的异构集合? 很好地概述了如何在不影响对象安全的情况下创建异构向量.

The code has some minor issues as well, namely that it lacks any kind of indirection for the trait. See What is the best way to create a heterogeneous collection of objects? for a good overview of how to make a heterogeneous vector when not fighting object safety.

说到对象安全有一个关于该主题的精彩博客系列,其中涵盖了您遇到的特定错误的详细信息.

Speaking of object safety, there's a great blog series on the subject, which covers the details of the specific error you are getting.

那么,我们能做什么?首先,我们可以更具体:

So, what can we do? For starters, we can be more specific:

let mut x: Vec<Box<PartialEq<u8>>> = Vec::new();

这是可行的,因为我们说向量中的所有内容都可以与 u8 进行比较,并且每个都可以进行比较并没有无限多的可能性.

This works because we are saying that everything in the vector can be compared to a u8, and there's not an open-ended infinite number of possibilities that each may be compared to.

你也可以实现一些特性来规定应该如何比较事物,然后使用它:

You could also implement some trait that dictates how things should be compared, and then use that:

trait Silly {
    fn silly(&self) -> usize;
}

impl Silly for u8 {
    fn silly(&self) -> usize { *self as usize }
}

impl Silly for bool {
    fn silly(&self) -> usize { 1 }
}

fn main() {
    let mut x: Vec<Box<Silly>> = Vec::new();
}

这篇关于是否有可能实现 Eq 类型的异构向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆