Can I convince the compiler that a function won't ever return?

Suppose I have a function that I use to close a resource and then panic.

fn close_and_panic(resource) {
   drop(resource);
   panic!("error message");
}

I need to close the resource first because otherwise the display is in an unusable state to print the error message. The problem is that resource is moved to the function and the compiler doesn't realize that this function won't ever return. So if I try to use the resource in the caller after this function may be called, I get a borrow of moved value error. E.g.,

fn foo(resource) {
   match resource.do_something() {
      Ok(_) => {}
      Err() => close_and_panic(resource)
   }
   resource.do_something_else(); // <--- Use after move error
}

I can't borrow the resource because then I won't be able to drop() it. It needs to be a full move. Can I somehow tell the compiler that close_and_panic() will never return?

Thanks.

Use ! as your return type.

fn close_and_panic(resource) -> ! {
   drop(resource);
   panic!("error message");
}
7 Likes

Try

fn close_and_panic(resource) -> ! {
   drop(resource);
   panic!("error message");
}
4 Likes

And Happy Birthday to you!

2 Likes

And this is the documentation you want to read on the "never type"/!.

6 Likes

The "Never Type"! What a revelation! Thank you all.

Oh, I think I might understand the never type now. Thanks for your question.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.