首页 > 解决方案 > “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 什么都不能返回

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

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

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

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

标签: rustembedded

解决方案


为了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");
        }
    }
}

推荐阅读