I started writing C again after professionally doing Scala and Python for quite some time. After using Scala's "Option" and "Either" error handling patterns and recently tasted the Rust way I wanted something similar in C. So I came up with something like this:
typedef struct {
int age;
char* name;
} User;
typedef struct {
char* error;
User* value;
} UserResult;
UserResult get_user() {
/* Some complicated user fetching process .. that fails */
return (UserResult) { .error = "403 Unauthorized\n" };
}
int main(void) {
UserResult res = get_user();
if (res.error)
handle_error(res.error);
if (res.value)
do_something(res.value);
/* ... */
return 0;
}
But this isn't really safe (we could access invalid pointers). How can I get something similar than the Scala or Rust way of handling errors in C ?
EDIT: corrected UserResult field name "value"