我写了一个简单的 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
调用应该返回的类型。在不知道 connect
和 send
类型的情况下很难确定,但我猜这是因为你的 lambda block 的主体(可能是错误的)导致了无类型。
Rust 中每个 block 的类型由它的“尾表达式”决定,尾表达式是通过将分号从最终语句中去掉来创建的。据推测,send
返回 result
类型,这就是您在其上使用 result::chain
的原因 - 因此整个表达式的结果是发送
的结果。为使其正常工作,send
表达式不应以分号结尾。然后您的 lambda block 将返回 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);
}
当然可以替换 connect
和 send
实际使用的任何类型。在将所有内容分开的过程中的某个时刻,您会发现您和编译器不同意的地方。
关于使用rust 错误 "cannot determine a type for this expression",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9660086/