Allowing for main() to be divergent in embedded environments

This came to me because of my embedded programming focus and the recent discussion of changing the return value of main() to allow for the question-mark operator to be used within it instead of .unwrap().

On microcontrollers with no OS on them, returning from main is generally A Bad Thing™ as it causes the processor to reset and the firmware to start over again. Since a big part of Rust is embedded logic into the type system, I’m wondering if supporting main() as a diverging function could be useful. The main in embedded programs commonly looks like the following (where I’ve applied the divergent return value):

#[no_mangle]
pub extern fn main() -> ! {
    loop {}
}

This would then catch for any situations during programming when the loop is returned from. Now there many be some people who comment that returning from main can be useful to issue a software reset during catastrophic failure. Well, this isn’t the “right” way to do this. Instead one should be explicit and call whatever assembly instruction exists on the target to issue a software reset instead of using this kind of implicit software reset functionality of returning from main.

Any thoughts on this?

Whoops, I didn’t actually test this before I ran it. Since we have the #![no_main] set in this file as well, it looks like the normal main function type rules don’t apply, or at least it lets us compile this.

Seems related to this thread, which proposed allowing main to have other return types for a totally different reason.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.