【问题标题】:unable to run function module when "fn main() -> ! {...}"“fn main() -> ! {...}”时无法运行功能模块
【发布时间】:2020-10-28 02:19:06
【问题描述】:

在这里学习一些 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 `()` 

关于如何修复它的任何想法?

【问题讨论】:

  • 我很困惑。为什么要尝试使用 never 类型!,表示函数永远不会返回,当它返回时(大约 20 秒后)?
  • ! 意味着你需要永远循环,如果你想显式循环 5 次,然后这样做并在之后添加一个不同的无限循环。
  • 正如我所读到的,当在 MCU 中使用此代码时(没有打印,但读取传感器),它需要有“从不!”关于主要功能!如果我错了,请纠正我。我只想在主函数之外放置一些逻辑(在本例中为循环)。 @loganfsmyth 如果我删除循环计数,情况是一样的!有没有办法让“dothings”函数什么都不返回?

标签: rust embedded


【解决方案1】:

为了让main 编译成-> ! 类型,必须知道主体不会返回——在这种情况下,主体是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");
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2019-09-25
    • 1970-01-01
    相关资源
    最近更新 更多