我有一个简单的程序,我试图实现多态帐户类型:
enum AccountType {
INVALID,
TYPE1,
TYPE2,
}
trait Account {
fn get_name(&self) -> String;
fn get_type(&self) -> AccountType;
}
struct Accounts {
accounts: Vec<Box<Account>>,
}
impl Accounts {
fn new() -> Accounts {
let accs: Vec<Box<Account>> = Vec::new();
Accounts { accounts: accs }
}
fn add_account<A: Account>(&self, account: A) {
self.accounts.push(Box::new(account));
}
}
fn main() {
let accounts = Accounts::new();
}
(铁锈游乐场)
当我编译它时,我看到以下错误:
error[E0310]: the parameter type `A` may not live long enough
--> src/main.rs:23:28
|
22 | fn add_account<A: Account>(&self, account: A) {
| -- help: consider adding an explicit lifetime bound `A: 'static`...
23 | self.accounts.push(Box::new(account));
| ^^^^^^^^^^^^^^^^^
|
note: ...so that the type `A` will meet its required lifetime bounds
--> src/main.rs:23:28
|
23 | self.accounts.push(Box::new(account));
| ^^^^^^^^^^^^^^^^^
我尝试过向该类型添加生命周期,但找不到正确的方法。如果这不是在 Rust 中进行多态性的正确方法,请告诉我。
我将尝试给出更彻底的答案:这个问题与accounts
成员Accounts
. Vec<Box<Account>>
在这种情况下相当于Vec<Box<Account + 'static>>
,即该框不能包含对堆栈上数据的任何引用。另一方面,声明add_account
不限制类型的生命周期:它相当于fn add_account<'a, A: Account + 'a>(&self, account: A) {
.
解决方案是确保 A 型的寿命足够长。最简单的方法就是添加A: 'static
错误消息中建议的绑定(fn add_account<A: Account + 'static>(&self, account: A) {
).
如果您不想复制帐户数据,您可以执行更复杂的操作,如下所示:
struct Accounts<'a> {
accounts: Vec<&'a Account + 'a>
}
impl<'a> Accounts<'a> {
fn new() -> Accounts<'a> {
Accounts { accounts: Vec::new() }
}
fn add_account<A: Account + 'a>(&mut self, account: &'a A) {
self.accounts.push(Box::new(account));
}
}
不过,此时您拥有的数据结构可能比您实际需要的更通用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)