Parameter type may not live long enough

前端 未结 2 1248
失恋的感觉
失恋的感觉 2021-01-14 05:24

I have a simple program where I am trying to implement a polymorphic account type:

enum AccountType {
    INVALID,
    TYPE1,
    TYPE2,
}

trait Account {
          


        
2条回答
  •  难免孤独
    2021-01-14 05:47

    I'll try to give a more thorough answer: the issue has to do with the definition of the accounts member of Accounts. Vec> in this context is equivalent to Vec>, i.e. the box can't contain any references to data on the stack. On the other hand, the declaration of add_account doesn't restrict the lifetime of the type: it's equivalent to fn add_account<'a, A: Account + 'a>(&self, account: A) {.

    The solution is to make sure the type A lives long enough. The simplest approach is to just add the A: 'static bound suggested in the error message (fn add_account(&self, account: A) {).

    If you don't want to copy the Account data, you can do something more complicated, like this:

    struct Accounts<'a> {
        accounts: Vec<&'a Account + 'a>
    }
    
    impl<'a> Accounts<'a> {
        fn new() -> Accounts<'a> {
            Accounts { accounts: Vec::new() }
        }
    
        fn add_account(&mut self, account: &'a A) {
            self.accounts.push(Box::new(account));
        }
    }
    

    At this point, though, you have a data structure which is probably more general than you actually need.

提交回复
热议问题