我有一个简单的程序,其中我正在尝试实现多态账户类型:
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中实现多态的正确方式,请告诉我。
Vec<Box<Account>>
等同于Vec<Box<Account + 'static>>
的意思吗?我的意思是,代码中的哪些部分表明它等同于Vec<Box<Account + 'static>>
? - soupybionics'static
时发生了什么? - Crispy13