Need type on top of generics

I have a function where I need to return vector of requests. Each request is instance of enum:

pub enum Request<T> {
    Print(String),
    SingleSelect(T),
}

The issue is that it seems to be not possible to implement the type, which would allow to return vector of Request::SingleSelect with different types:

#[derive(Debug)]
pub enum HandlerOutput {
    Data(String),
    ConnectionRequest(String, u16),
    Freeze,
    Void,
    Drop,
}

pub enum Request<T> {
    Print(String),
    SingleSelect(T),
}

// this line is not work, because here expected a generic type
pub type HandlerResult = AnyResult<(HandlerOutput, Vec<Request>)>;

fn test() -> HandlerResult {
    let request1 = Request::Print("test".to_string());
    let request2 = Request::SingleSelect(vec![1, 2, 3, 4, 5]);
    let request3 = Request::SingleSelect(vec!["one", "two", "three", "four", "five"]);
    
    Ok(vec![request1, request2, request3])
}

So I got this error:

error[E0107]: missing generics for enum `Request`
  --> src/main.rs:17:56
   |
17 | pub type HandlerResult = AnyResult<(HandlerOutput, Vec<Request>)>;
   |                                                        ^^^^^^^ expected 1 generic argument
   |
note: enum defined here, with 1 generic parameter: `T`
  --> src/main.rs:12:10
   |
12 | pub enum Request<T> {
   |          ^^^^^^^ -
help: add missing generic argument
   |
17 | pub type HandlerResult = AnyResult<(HandlerOutput, Vec<Request<T>>)>;

This is example for reproduce.

Could somebody explain if this is possible to fix the issue or this is the same mechanism like generally vectors works ?

If you know the set of all possible T before hand, you can do something like

pub enum Request {
  Print(String),
  SingleSelect_u32(Vec<u32>),
  SingleSelect_string(Vec<String>),
}

If not, but all the T satisfies some trait, you can do

pub enum Request {
  Print(String),
  SingleSelect(Vec<Box<dyn Request_T>>)
}

pub trait Request_T { ... }

impl Request_T for String{}

impl Request_T for u32 {}
3 Likes