【发布时间】:2018-07-30 22:26:15
【问题描述】:
我正在尝试对类似数据框的结构进行建模。我知道如何在这里使用enums,但我正在探索它如何类似于 C#/Python/等。
我尝试关注Rust Trait object conversion,但没有成功:
use std::any::{Any};
use std::fmt::Debug;
pub trait Value: Any + Sized {
fn as_any(&self) -> &Any {
self
}
fn as_any_mut(&mut self) -> &mut Any {
self
}
}
impl Value for i32 {}
#[derive(Debug)]
struct Frame {
data: Vec<Box<Any>>,
}
fn make_int(of: Vec<i32>) -> Frame {
let data = of.into_iter().map(|x| Box::new(x.as_any())).collect();
Frame {
data: data,
}
}
编译器抱怨:
error[E0277]: the trait bound `std::vec::Vec<std::boxed::Box<std::any::Any>>: std::iter::FromIterator<std::boxed::Box<&std::any::Any>>` is not satisfied
--> src/main.rs:40:61
|
40 | let data = of.into_iter().map(|x| Box::new(x.as_any())).collect();
| ^^^^^^^ a collection of type `std::vec::Vec<std::boxed::Box<std::any::Any>>` cannot be built from an iterator over elements of type `std::boxed::Box<&std::any::Any>`
|
= help: the trait `std::iter::FromIterator<std::boxed::Box<&std::any::Any>>` is not implemented for `std::vec::Vec<std::boxed::Box<std::any::Any>>`
【问题讨论】:
-
一个数组与一个
Vec不同。 -
你能解释一下你对错误信息的不理解吗?对我来说似乎很清楚:
Box<Any>!=Box<&Any>。 -
请查看如何创建minimal reproducible example,然后查看edit 您的问题以包含它。存在许多与您的问题无关的类型,因此它不是Minimal。
-
@Shepmaster 我了解错误,但不知道如何解决。如果我放 Box::new(x.as_any()) 为什么不匹配 Vec
>? -
是的,您需要提供足够的代码来重现问题(Complete),但这就是您应该提供的全部内容(Minimal)。如果您阅读minimal reproducible example 的帮助页面,所有这些都会得到解释。
标签: arrays rust generic-programming