Jin*_*Jin 1 rust rust-obsolete
这编译:
use std::num::pow;
pub fn main() {
let (tx, rx): (Sender<u64>, Receiver<u64>) = channel();
let square_tx = tx.clone();
let square = proc() {
let mut x = 1u;
loop {
square_tx.send(pow(2u64, x));
x += 1;
}
};
let printer = proc() {
loop { println!("Received: {}", rx.recv()); }
};
spawn(square);
spawn(printer);
}
Run Code Online (Sandbox Code Playgroud)
但如果我注释掉spawn(square)
,会引发以下错误:
error: unable to infer enough type information about `_`; type annotations required
let square = proc() {
^
Run Code Online (Sandbox Code Playgroud)
如果没有产卵就无法推断spawn()
a的类型信息有什么特别之处proc()
?
spawn
采用一个proc()
没有参数和返回值的过程()
,因此编译器可以推断square
必须具有该类型才能使程序有效.
最后一个表达式proc
是loop {}
,没有break
或者return
,所以编译器可以看到闭包永远不会正确返回.也就是说,它可以假装具有任何类型的返回值.由于返回类型不受限制,编译器无法分辨出哪个是必需的,因此会抱怨.
只有平原就可以看到类似的行为loop {}
.
fn main() {
let x = loop {};
// code never reaches here, but these provide type inference hints
// let y: int = x;
// let y: () = x;
// let y: Vec<String> = x;
}
Run Code Online (Sandbox Code Playgroud)
<anon>:2:9: 2:10 error: unable to infer enough type information about `_`; type annotations required
<anon>:2 let x = loop {};
^
Run Code Online (Sandbox Code Playgroud)
(同样的事情发生在编译器可以告诉的任何事情都不会让控制流继续下去,例如let x = panic!();
,let x = return;
.)
取消注释其中y
一行将使程序编译.