ws-rs:E0271r:expected(),发现枚举`std :: result :: Result`

时间:2017-09-02 22:46:57

标签: enums websocket rust fibonacci

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

 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
}

1 个答案:

答案 0 :(得分:1)

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

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的类型,因为它没有直接传递给具有已知类型签名的方法;因此编译器无法推断其类型,我们需要明确提供它。