generics - 如何暗示返回一个在 Rust 中使用动态调度的值?
问题描述
=== 编辑于 2018-04-28 10:17AM ===
感谢您的回答,但是当我使用 遵循您的回答时Box<>
,我发现它仍然无法正常工作。
https://play.rust-lang.org/?gist=211845d953cd9012f6f214aa5d81332d&version=stable&mode=debug
错误信息是:
error[E0038]: the trait `Entity` cannot be made into an object
--> src/main.rs:20:5
|
20 | entities: Vec<Box<Entity>>
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Entity` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`
所以我想知道是cannot be made into an object
什么?我该如何解决这个问题?
===原始答案===
我想用普通类实现像Java的接口/抽象类这样的层次结构:
trait Entry {
fn new() -> Entry;
}
struct EntryA {}
impl Entry for EntryA {
fn new() -> EntryA {
// I want to return EntryA rather Entry here, just like dynamic dispatch in Java
}
}
struct EntryB {}
impl Entry for EntryB {
fn new() -> EntryB {
// Another Entry struct
}
}
现在我想创建一个或一个包含sVec
的数组:Entry
fn create_an_array() -> [Something to write here] {
let mut vec: Vec<Entry> = vec![];
let ea = EntryA::new();
let eb = EntryB::new();
vec.push(ea);
vec.push(eb);
vec
}
当我使用Vec
created bycreate_an_array()
时,我得到的所有元素都只能显示Entry
外观,而不是详细显示子类。
然而,主要的问题是,当重写函数时,Rust 不仅考虑参数,还考虑返回类型(Rust 你为什么这样做?!),所以我不能重写或者因为函数的返回类型new()
与特征。EntryA
EntryB
Entry
如何处理动态调度的问题?
解决方案
推荐阅读
- php - 试图在 fetch_assoc PHP、MYSQLI 中执行 fetch_assoc
- typescript - 添加redux-persist后,我无法再获取redux store的状态
- javascript - 尝试在 Redux 中保留一些数据时出现“未捕获的 TypeError:e 不是函数”
- node.js - 无法在 express 中的 req.session 中设置 userId?
- reactjs - React Native Rainbow-me/Charts 绑定
- python - 具有动态属性名称的类的类型注释
- python - Windows 终端错误,pyinstaller 无法识别?
- c - 目标文件符号表中局部符号的用途是什么?
- sql - 使用 powershell 在 ssis 服务器 sql 作业上使用 sql 查询
- datatable - 在 PowerBI 的表格中将每个月显示为一列