在这里学习一些 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/