2012-03-11 58 views
0

我寫了一個簡單的生鏽程序。生鏽的錯誤「無法確定此表達式的類型」

fn main(){ 
    let port = 80; 
    result::chain(connect("localhost", port as u16)) {|s| 
    send(s,str::bytes("hello world")); 

};

它有一些錯誤。

macmatoMacBook-Air-2:rust-http kula$ rustc http.rs 
http.rs:40:4: 40:52 error: cannot determine a type for this expression 
http.rs:40  result::chain(connect("localhost", port as u16)) {|s| 
      ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
error: aborting due to previous errors 

發生了什麼事?

回答

4

編譯器未能推斷出該調用result::chain應該返回的類型。在不知道connectsend的類型的情況下很難確定,但我猜測這是因爲你的lambda塊的主體(可能是錯誤地)導致了nil類型。

鏽的每個塊的類型由它的「尾部表達式」決定,尾部表達式是通過將最終語句的分號留下來創建的。據推測,send返回result類型,這就是爲什麼你使用result::chain - 因此,整個表達式的結果是send的結果。爲了使這項工作send表達式不應以分號結尾。然後你的lambda塊將返回send的結果。

像這樣的東西可能會更好地工作:

fn main(){ 
    let port = 80; 
    result::chain(connect("localhost", port as u16)) {|s| 
     send(s,str::bytes("hello world")) // <- no semicolon 
    }; 
} 

當類型推斷失敗有時可以幫助分解表現爲較小的一系列語句並插入明確的類型,直到你找出其中的類型不匹配起來正確。如果我打這樣的事情,不能目測了一段時間弄明白,那我就開始重寫它像

fn main(){ 
    let port = 80; 
    let conn_result: result::t<connection, str> = connect("localhost", port as u16); 
    let send_fn = [email protected](s: connection) -> result::t<str, str> { 
     let send_result: result<str, str> = send(s,str::bytes("hello world")); 
     ret send_result; 
    }; 
    let res: result<str, str> = result::chain(conn_result, send_fn); 
} 

任何類型connectsend實際使用過程中代入的。在將所有內容分開的過程中,你會發現你和編譯器不同意的地方。

相關問題