Adding trait and using existing method

Is it possible to add

fn time_since_epoch(st: &SystemTime) -> u128 {
    match st.duration_since(SystemTime::UNIX_EPOCH) {
        Ok(d) => { d.as_nanos() },
        Err(e) => panic!("{}", e)
    }
}

as a method to the std::time::SystemTime struct so that I can call st.since_epoch()?
(When I define a trait that I want to add to SystemTime, the problem I have is that self.duration_since(...) is not implemented via a trait but via impl SystemTime {...}; i.e. the trait doesn't see duration_since(...)).

You can define a trait that implements this such as

trait TimeExt{
    fn since_epoch(&self)->u128;
}

and then implement it on SystemTime

impl TimeExt for SystemTime{
 fn since_epoch(&self)->u128{
    match self.duration_since(SystemTime::UNIX_EPOCH) {
        Ok(d) => { d.as_nanos() },
        Err(e) => panic!("{}", e)
      }
    }
}

then use it as

let x = get_time_somehow();
x.since_epoch();

Dont forget to use it in the file you want to use this extension tho

1 Like

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.