我正在学习 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();
}
更多详情:
关于enums - ws-rs : E0271r: expected (), 找到枚举 `std::result::Result`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46018866/