質問

私は簡単なrustプログラムを書いています。

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

何があったの?

役に立ちましたか?

解決

コンパイラは、この呼び出しが実行された型を推測できませんでした result::chain 戻ってくることになっています。の種類を知らずに確実に伝えるのは難しいです connectsend, 、しかし、私はそれがあなたのラムダブロックの本体が(おそらく誤って)nil型になっているからだと思います。

Rustのすべてのブロックのタイプは'tail expression'によって決定され、末尾の式は最後の文のセミコロンをオフにすることによって作成されます。おそらく, 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 =  fn@(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 実際に使用します。すべてを引き離す過程のある時点で、あなたとコンパイラがどこに同意しないかがわかります。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top