rust - “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 `()`
关于如何解决它的任何想法?
解决方案
为了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");
}
}
}
推荐阅读
- javascript - 从承诺中导出数组,但在另一个文件中需要时不加载?
- javascript - scrollIntoView() 在控制台中有效,但在站点代码中无效
- python - 将单行从一个 csv 复制到另一个 csv 文件
- system - CLIPS 规则多次触发
- javascript - 一键执行php函数和javascript函数
- python-3.x - 在python中列出2个范围和n个元素
- python - 在 BeautifulSoup 中选择嵌套的第三个孩子
- android - 如果密码输入错误次数过多,我可以让我的安卓手机自动恢复出厂设置吗?
- android - 在 Android 应用中实现加速度计
- git - GitHub 子模块 - 指向外部但更改 1 文件