小编ryt*_*one的帖子

使用 async (tokio) rust-websocket 在客户端之间共享可变状态

我正在使用 rust-websocket 及其基于 Tokio 的异步系​​统在 Rust 中编写一个 websocket 服务器。我可以很好地为客户服务,但是,我不知道如何在客户之间共享可变状态。以下是一些(部分)代码演示此问题:

let mut core = Core::new().unwrap();
let handle = core.handle();
let server = Server::bind("localhost:62831", &handle).unwrap();

let mut state = State{
    ...
};

let f = server.incoming()
    .map_err(|InvalidConnection {error, ..}| error)
    .for_each(|upgrade, _)| {
        let f = upgrade.accept()
            .and_then(|s, _| {
                let ctx = ClientContext{
                    // some other per-client values
                    state: &mut state,
                }
                ...
                return s.send(Message::binary(data).into())
                    .and_then(move |s| Ok(s, ctx)); // this could be the complete wrong way to insert context into …
Run Code Online (Sandbox Code Playgroud)

asynchronous websocket rust rust-tokio

5
推荐指数
1
解决办法
1877
查看次数

使用借位作为相关特征类型

此代码有效:

struct Test {
    val: String,
}

impl Test {
    fn mut_out(&mut self) -> &String {
        self.val = String::from("something");
        &self.val
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,更通用的实现不起作用:

struct Test {
    val: String,
}

trait MutateOut {
    type Out;
    fn mut_out(&mut self) -> Self::Out;
}

impl MutateOut for Test {
    type Out = &String;

    fn mut_out(&mut self) -> Self::Out {
        self.val = String::from("something");
        &self.val
    }
}
Run Code Online (Sandbox Code Playgroud)

编译器无法推断字符串借用的生命周期:

error[E0106]: missing lifetime specifier
  --> src/main.rs:13:16
   |
11 |     type Out = &String;
   |                ^ expected lifetime parameter …
Run Code Online (Sandbox Code Playgroud)

rust

2
推荐指数
1
解决办法
66
查看次数

标签 统计

rust ×2

asynchronous ×1

rust-tokio ×1

websocket ×1