2017-09-02 86 views
0

我正在學習Rust,我試圖製作一個WebSocket服務器來計算n的Fibonacci併發送結果背部。我發現了錯誤:ws-rs:E0271r:expected(),找到枚舉`std :: result :: Result`

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

哇,這是一個非常混亂編譯器錯誤。考慮提交一個錯誤。 ;) 請參閱我的意見,描述修復。

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的類型,因爲它沒有直接傳入具有已知類型簽名的方法;所以編譯器不能推斷它的類型,我們需要明確提供它。