Sorry if the answer to the following is straight forward but i can't seem to understand it.
I need to create a swarm and return the swarm to the main function but i don't know how to return a generic struct such as the 'P2p' struct.
Traits are used for abstracting methods so i cannot declare one to abstract the structs' attributes.
ps: swarm is of type struct ExpandedSwarm<"something that depends on the behaviour and transport">
pps: Thank you for any input.
fn create_swarm<T>() -> Result<T, Box<dyn Error>> {
let local_key = identity::Keypair::generate_ed25519();
let local_peer_id = PeerId::from(local_key.public());
println!("Local peer id --> {}", local_peer_id);
let transport = block_on(libp2p::development_transport(local_key))?;
let behaviour = Ping::new(PingConfig::new().with_keep_alive(true));
let local_swarm = Swarm::new(transport, behaviour, local_peer_id);
let p = P2p::new(local_swarm);
Ok(p)
}
struct P2p <T> {
swarm: T
}
impl <T> P2p<T> {
pub fn new(swarm: T) -> Self {
return Self{swarm}
}
}
If all of your swarm types implement the same trait, say
Swarmer
, you can box it, makeP2p
's swarm type aBox<dyn Swarmer>
and return typeResult<P2p, Box<dyn Error>>
.Otherwise, you need to think about how to abstract this. Each of the variables in the
create_swarm
function must have a fixed type known at compile time. That can be some sort of trait object (boxed or otherwise), but you're never going to just be able to return an object of arbitrary type. For example, every instance oftransport
will need to have a fixed, discernible type, and that will determine the type oflocal_swarm
(assuming it's generic) and hencep
.If you really need an arbitrary object that you can later downcast into the appropriate concrete type, you can use
Box<dyn Any>
(assuming your types implementAny
). This is like C'svoid *
, and can be useful where you need to pass different kinds of opaque data between cooperating functions with some oblivious functions in between. However, you won't really be able to call any sort ofSwarm
-specific methods on it.