本文介绍了参数类型的存在时间可能不够长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的程序,我试图在其中实现多态帐户类型:
I have a simple program where I am trying to implement a polymorphic account type:
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();
}
当我编译它时,我看到以下错误:
When I compile it, I see the following error:
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 中实现多态的正确方法,请告诉我.
I have tried adding lifetimes to the type but could not find the right way to do it. Please let me know if this is not the right way to do polymorphism in Rust.
推荐答案
编译器的建议确实有效.如果你写 add_account
如下:
The compiler's suggestion actually works. If you write add_account
as follows:
fn add_account<A: Account + 'static>(&mut self, account: A) {
self.accounts.push(Box::new(account));
}
您的代码可以编译.(顺便说一句,这里需要&mut self
,而不是&self
)
your code compiles. (Incidentally, you need &mut self
, not &self
here)
这篇关于参数类型的存在时间可能不够长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!