I am pretty new to Rust and I am working on a crate that will provide an API for using a Discord bot to run drafts of various things (i.e. fantasy sports, Pokemon leagues etc). I have a public trait, DraftItem, which end users can implement on whatever struct they create to hold information about a selection in their draft (a football player, a Pokemon, etc). This is the trait definition:
pub trait DraftItem {
fn name(&self);
}
It's very simple so far, it might need some other methods eventually but for now it just needs to return a name that can be sent via a Discord message.
I also have an ActivePlayer struct that holds DraftItems that the player has queued up or locked in:
pub struct ActivePlayer {
queue: Vec<Box<dyn DraftItem>>,
...
}
impl ActivePlayer {
pub fn add_to_queue<'a, T>(&mut self, item: T)
where
T: DraftItem + 'a,
{
self.queue.push(Box::new(item));
}
}
This code won't compile, giving the error E0310: the parameter type T may not live long enough
. I am not super comfortable with either trait bounds or lifetimes, so I'm struggling to understand why my lifetime annotation isn't working properly. The compiler suggests annotating T with 'static
but I definitely don't want the DraftItems to live for the whole runtime. Do I need to annotate my DraftItem or ActivePlayer definitions with lifetimes? Is the compiler error specifically because I'm trying to put the DraftItem in a box, or is this a more general problem with the design of my code?