Rust 如果未传递到spawn()中,则无法推断proc()的类型信息

Rust 如果未传递到spawn()中,则无法推断proc()的类型信息,rust,rust-obsolete,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)

这包括:

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);
}

spawn()
有什么特别之处,使得在不生成的情况下无法推断
proc()
的类型信息?

spawn
采用
proc()
即没有参数和返回值的过程,因此,编译器可以推断
square
必须具有该类型才能使程序有效

proc
中的最后一个表达式是
循环{}
,没有
中断
返回
,因此编译器可以看到闭包永远不会正确返回。也就是说,它可以假装有任何类型的返回值。由于返回类型是不受限制的,编译器无法判断需要哪种类型,因此会抱怨

只需一个普通的
循环{}
就可以看到类似的行为

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;
}
fn main(){
设x=loop{};
//代码永远不会到达这里,但它们提供了类型推断提示
//设y:int=x;
//设y:()=x;
//设y:Vec=x;
}

(编译器可以告诉你的任何事情都不会让控制流继续,例如
让x=panic!();
让x=return;


取消注释其中一个
y
行将允许程序编译。

spawn
采用
proc()
即没有参数和返回值的过程,因此编译器可以推断
square
必须具有该类型才能使程序有效

proc
中的最后一个表达式是
循环{}
,没有
中断
返回
,因此编译器可以看到闭包永远不会正确返回。也就是说,它可以假装有任何类型的返回值。由于返回类型是不受限制的,编译器无法判断需要哪种类型,因此会抱怨

只需一个普通的
循环{}
就可以看到类似的行为

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;
}
fn main(){
设x=loop{};
//代码永远不会到达这里,但它们提供了类型推断提示
//设y:int=x;
//设y:()=x;
//设y:Vec=x;
}

(编译器可以告诉你的任何事情都不会让控制流继续,例如
让x=panic!();
让x=return;

取消注释
y
行之一将使程序编译

<anon>:2:9: 2:10 error: unable to infer enough type information about `_`; type annotations required
<anon>:2     let x = loop {};
                 ^