我正在创建一个具有两个参数的 API 函数,我希望第二个参数的类型取决于第一个参数的值,例如:
enum Component{
Cpu,
Disk
}
struct CpuState {
pub frequency: u64
}
struct DiskState {
pub speed: u64
}
type Handler<T> = Box<dyn Fn(T) -> Box<dyn Future<Output = String> + Send> + Send + Sync>;
// the type of parameter(`<T>`) in handler is depends on the component you chosen.
fn monitor(component: Component, handler: Handler){}
我尝试过的方法是使用特征,但不起作用:
trait StateEventHandler {
type Component;
type Handler;
}
impl StateEventHandler for CpuState {
type Component = Component::Cpu; // error: expected type, found variant `Component::Cpu`
not a type
type Handler = Handler<CpuState>;
}
impl StateEventHandler for DiskState {
type Component = Component::DiskState; // error like above
type Handler = Handler<DiskState>;
}
fn monitor<T: StateEventHandler>(component: T::Component, handler: T::Handler){}
怎么办呢?