I am using a crate which has a struct (lets call it ChosenContainer
) that I want to use. I want to store a ChosenContainer
in my OwnContainer
struct. But I am not sure what the type of the stored value should be.
I made a small code snippet which corresponds to my situation. I tried all different types in my OwnContainer
.
- I tried
Box
ing theChosenContainer
struct:c_container: Box<ChosenContainer<dyn Chosen>>
- I tried trait bounds
c_container: ChosenContainer<T>
whereT: Chosen
- I tried combining them.
- Googled for a few hours.
I have no idea how to do this. Is this even possible?
// --- code from a foreign crate simplified below --- //
pub struct Thing;
pub trait Chosen {}
impl Chosen for Thing {}
pub fn get_chosen() -> impl Chosen {
Thing
}
pub struct ChosenContainer<C: Chosen> {
chosen: C,
}
impl<C: Chosen> ChosenContainer<C> {
pub fn new(chosen: C) -> Self {
ChosenContainer { chosen }
}
}
// --- my code so we can edit stuff below --- //
// should own a ChosenContainer
struct OwnContainer {
c_container: ChosenContainer<dyn Chosen>,
}
impl OwnContainer {
fn new() -> Self { // I want to keep function signiture
let c = get_chosen();
let c_container = ChosenContainer::new(c);
OwnContainer {
c_container,
}
}
}
fn main() {
// should be able to create one like this:
let own_container = OwnContainer::new();
}
Any help would be greatly appreciated.