"fn main() -> ! {...}" 时无法 运行 功能模块

unable to run function module when "fn main() -> ! {...}"

在这里学习一些 Rust..

我可以在命令行上执行此操作!

// main.rs ------------
mod attach;

fn main(){
    attach::dothings();
}

// attach.rs ------------
use std::{thread, time};

pub fn dothings(){
    let mut cnt = 1;
    loop {
        // !I could blink a led here or read a sensor!
        println!("doing things {} times", cnt);
        thread::sleep(time::Duration::from_secs(5));
        cnt = cnt +1;
        if cnt == 5 {break;}
    }
}

但是做嵌入式的时候,main不能return什么都没有

fn main() -> ! {...}

使用类似代码时!我收到了这个错误。 (?隐式 return 是 ()?)

  | -------- implicitly returns `()` as its body has no tail or `return`
9 | fn main() -> ! {
  |              ^ expected `!`, found `()` 

有什么解决办法吗?

为了让 main 以类型 -> ! 编译,必须知道正文不是 return — 在这种情况下,正文是 attach::dothings(); 您需要给 dothings 相同的 return 类型:

pub fn dothings() -> ! { ... }

您还需要不 break 循环,否则它不是无限循环。这个版本会崩溃,你可能不希望你的嵌入式代码这样做,但它编译:


pub fn dothings() -> ! {
    let mut cnt = 1;
    loop {
        println!("doing things {} times", cnt);
        thread::sleep(time::Duration::from_secs(5));
        cnt = cnt +1;
        if cnt == 5 {
            todo!("put something other than break here");
        }
    }
}