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

mvc*_*rea 0 embedded rust

在这里学习一些 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;}
    }
}
Run Code Online (Sandbox Code Playgroud)

但是在做embedded的时候,main不能什么都返回

fn main() -> ! {...}
Run Code Online (Sandbox Code Playgroud)

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

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

关于如何解决它的任何想法?

Kev*_*eid 5

为了main使用 type 进行编译,-> !必须知道主体不会返回 - 在这种情况下主体是attach::dothings();您需要提供dothings相同的返回类型:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)