2

私には特徴があります:

pub trait Plugin {
    type Error: error::Error;

    fn handle(&mut self, client: & Client, message: Message) -> Result<(), Self::Error>;
}

このトレイトには多くの実装があります (各実装には特定のエラー タイプが含まれます)。

impl ::Plugin for first::Plugin {
    type Error = first::Error;

    fn handle(&mut self, client: & Client, message: Message) -> first::Result<()> {
        ...
        Ok(())
    }
}

impl ::Plugin for second::Plugin {
    type Error = second::Error;

    fn handle(&mut self, client: & Client, message: Message) -> second::Result<()> {
        ...
        Ok(())
    }
}

プラグインのベクトルを作成する必要があります:

let mut plugins: Vec<Box<Plugin<Error=_>>> = vec![
    Box::new(first::Plugin::new()),
    Box::new(second::Plugin::new()),
];

しかし、コードはこのエラーをスローします:

error: type mismatch resolving `<plugins::first::Plugin<'_> as plugin::Plugin>::Error == plugins::second::error::Error`:

コードを再編成しimpl trait Pluginて、関連付けられたタイプ (動的ディスパッチも) を含むプラグインのベクトル (動的ディスパッチ) を作成するにはどうすればよいimpl trait error::Errorですか?

--

完全なコードは次のとおりです。

fn main() {
    let mut plugins: Vec<Box<Plugin<Error = _>>> = vec![
        Box::new(first::Plugin::new()),
        Box::new(second::Plugin::new()),
    ];
}

pub trait Plugin {
    type Error: std::error::Error;

    fn handle(&mut self) -> Result<(), Self::Error>;
}

mod first {
    use std;

    pub struct Plugin;

    impl Plugin {
        pub fn new() -> Plugin {
            Plugin
        }
    }

    impl ::Plugin for Plugin {
        type Error = Error;

        fn handle(&mut self) -> Result<(), Error> {
            Ok(())
        }
    }

    #[derive(Debug)]
    pub struct Error;

    impl std::fmt::Display for Error {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
            write!(f, "{}", "first error")
        }
    }

    impl std::error::Error for Error {
        fn description(&self) -> &str {
            "first error"
        }
    }
}

mod second {
    use std;

    pub struct Plugin;

    impl Plugin {
        pub fn new() -> Plugin {
            Plugin
        }
    }

    impl ::Plugin for Plugin {
        type Error = Error;

        fn handle(&mut self) -> Result<(), Error> {
            Ok(())
        }
    }

    #[derive(Debug)]
    pub struct Error;

    impl std::fmt::Display for Error {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
            write!(f, "{}", "second error")
        }
    }

    impl std::error::Error for Error {
        fn description(&self) -> &str {
            "second error"
        }
    }
}

さびた遊び場

4

0 に答える 0