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

标签 rust embedded

在这里学习一些 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 `()` 
关于如何解决它的任何想法?

最佳答案

为了 main用类型编译-> ! ,必须知道主体不会返回 - 在这种情况下,主体是 attach::dothings();你需要给dothings相同的返回类型:pub fn dothings() -> ! { ... }你也不需要break循环,否则它不是无限循环。这个版本会 panic ,你可能不希望你的嵌入式代码这样做,但它确实编译:


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

关于rust - "fn main() -> ! {...}"时无法运行功能模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64565595/

相关文章:

c - 动态内存分配的流行用法

rust - 什么时候使用没有 Arc 的 Mutex?

rust - 从文件反序列化Toml时出现无用的错误

generics - 如何将外部关联类型强制为我的本地结构类型?

embedded - 爱特梅尔工作室 : How exacly do data breakpoints trigger?

c# - PHP 作为嵌入式脚本语言

rust - rust 裂偏移读取

rust - 你如何在使用rust 的 Windows 上使用带有 DLL 的 DynamicLibrary?

python - 创建一个网站来与嵌入式设备通信

C#,从 USART 接收字符缓冲区中提取 double