How to get system time without unwrap panicking?


fn now(clock: clock_t) -> Timespec {
let mut t = Timespec { t: libc::timespec { tv_sec: 0, tv_nsec: 0 } };
cvt(unsafe { libc::clock_gettime(clock, &mut t.t) }).unwrap();

If clock_gettime returns -1 (as it seems to on android when switching applications), this api just unwrap/panics - why !!! Why cant it just return an Option<> or Result<> and let user handle it ? I dont want my android app to crash, if time get fails ill deal with it.

Any other alternatives to SysteTime/Instant now() calls ? Any inputs will be apprecated!

1 Like

What about using nix::time::clock_gettime()?

1 Like

Alternatively you can catch it with catch_unwind.


The thing is i like the std::time because it takes care of handling all the OSes, I am writing a generic rust layer that will run on android, ios and windows. I think I will do what alice suggested and just to a catch_unwind

I think thats what I will end up doing, thanks alice!

well even that wont work since my function is defined as extern (so that I can call it as a native API from JNI) .. and looks like extern functions do not unwind (ie aborts) on default .. I guess i have no option but to just provide a time callback API myself for each platform. Its too bad that standard libraries contain apis that just unwrap or panic, standard libraries should just leave it up to the user to decide what they want to do and not make these decisions themslves ;-(

I encourage you to open an issue on the rustc bug-tracker if it doesn't already have one.


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.