在函数内创建的对象上设置特征边界

时间:2018-06-16 20:37:14

标签: generics rust traits serde

我正在使用ipc-channel crate,试图建立一个包含IpcOneShotServer的通用结构:

extern crate ipc_channel;
extern crate serde;

use ipc_channel::{ipc, Error};
use serde::{Deserialize, Serialize};

struct Supervisor<T> {
    server: ipc::IpcOneShotServer<T>,
}

impl<T> Supervisor<T>
where
    T: for<'de> Deserialize<'de> + Serialize,
{
    fn new() -> Result<Supervisor<T>, Error> {
        let (server, _) = ipc::IpcOneShotServer::new()?;
        Ok(Supervisor { server: server })
    }
}

fn main() {}

当我尝试编译此代码时,我收到以下错误

error[E0277]: the trait bound `for<'de> T: serde::de::Deserialize<'de>` is not satisfied
  --> src/main.rs:67:27
   |
67 |         let (server, _) = ipc::IpcOneShotServer::new()?;
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `for<'de> serde::de::Deserialize<'de>` is not implemented for `T`
   |
   = help: consider adding a `where for<'de> T: serde::de::Deserialize<'de>` bound
   = note: required by `<ipc_channel::ipc::IpcOneShotServer<T>>::new`

error[E0277]: the trait bound `T: serde::ser::Serialize` is not satisfied
  --> src/main.rs:67:27
   |
67 |         let (server, _) = ipc::IpcOneShotServer::new()?;
   |                           ^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `serde::ser::Serialize` is not implemented for `T`
   |
   = help: consider adding a `where T: serde::ser::Serialize` bound
   = note: required by `<ipc_channel::ipc::IpcOneShotServer<T>>::new`

我不确定我在这里失踪了什么。我已经TDeserialize限制了特征Serialize。我认为通过绑定这两个其他特征在impl中的特征,这将告诉类型检查器,只要Supervisor类型T实现DeserializeSerialize可以安全地拨打ipc::IpcOneShotServer::new()

0 个答案:

没有答案