我写了一个简单的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, ,但我会猜测这是因为你的lambda块的主体(可能是错误的)导致nil类型。

Rust中每个块的类型都由它的"尾表达式"决定,尾表达式是通过在最终语句中留下分号来创建的。据推测, 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