enums - ws-rs : E0271r: expected (), 找到枚举 `std::result::Result`

标签 enums websocket rust fibonacci

我正在学习 Rust,我正在尝试制作一个 WebSocket 服务器来计算 n 的 Fibonacci 并将结果发回。我收到错误:

 expected (), found enum `std::result::Result`

这是我的代码(带有注释):

extern crate ws;// add websocket crate
extern crate num;// add num crate (to handle big numbers)
extern crate regex;// regex crate

use ws::listen;
use num::bigint::BigUint;
use num::traits::{Zero, One};
use std::env;
use std::mem::replace;// used to swap variables

fn main() {
    let re = regex::Regex::new("[0-9]+").unwrap();// regex to check if msg is a number.
    listen("0.0.0.0:8080", |conn| {// this is where the arrows in the error message points to
        move |msg| {
            if re.is_match(msg) {// check if message matches the regex
                let num: i64 = msg.parse().unwrap();// set num to the msg as an integer
                conn.send(ws::Message::Text(fib(num).to_string()));// create a new ws message with the Fib of num
            }
        }
    }).unwrap();
}

fn fib(n: i64) -> BigUint {// fibonacci function
    let mut f0 = Zero::zero();
    let mut f1 = One::one();
    for _ in 0..n {
        let f2 = f0 + &f1;
        f0 = replace(&mut f1, f2);
    }
    f0
}

最佳答案

哇,这是一个非常令人困惑的编译器错误。考虑提交错误。 ;) 请参阅我描述修复的评论。

fn main() {
    listen("0.0.0.0:8080", |conn| {
        // Needs to return a `Result` on all code paths.
        // You were missing an `else`.
        move |msg: ws::Message| {
            // Need to extract text before parsing.
            let text = msg.into_text().unwrap();
            // Don't need regex -- parse and check success.
            match text.parse() {
                Ok(num) => conn.send(ws::Message::Text(fib(num).to_string())),
                Err(err) => Ok(()), // Or return an error if you prefer.
            }
        }
    }).unwrap();
}

更多详情:

  • listen()必须返回实现 Handler 的东西.
  • Handler为所有 F: Fn(Message) -> Result<()> 实现.所以你的方法需要返回一个 Result<()>在所有代码路径上。
  • 概念上,Handler也可以为其他东西实现。编译器无法推断 msg 的类型因为它没有直接传递给具有已知类型签名的方法;因此编译器无法推断其类型,我们需要明确提供它。

关于enums - ws-rs : E0271r: expected (), 找到枚举 `std::result::Result`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018866/

相关文章:

javascript - WebSocket 的 fetch 的 "credentials: ' include '"or XMLHttpRequest' s "withCredentials"是否有等效项?

rust - 借入时暂时值(value)下降

python - Python中的TypeError在反射(reflect)的数字仿真器(例如__radd__)中使用PyAny作为Rust pyo3 pyclass结构

.net - C# - 都是枚举常量吗?

android - 如何使用 | 生成枚举值在他们中

windows-phone-7 - 将枚举保存到IsolatedStorageSettings

java - Kotlin中Sealed类和继承原则有什么区别?

angular - MessageEvent 的访问字段

websocket - Thrift 支持通过 websocket 发送数据吗?

rust - 如何获取存储在具有引用原始生命周期的结构中的引用?