我正在学习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
}
答案 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();
}
进一步详情: