I have a function that returns the compound duration based on an usize
input:
pub fn format_dhms(seconds: usize) -> String
If the input is 6000000
:
println!("{}", format_dhms(6000000));
It returns:
69d10h40m
This works when the input is a number, but when I use the output of another function with a fixed type, I need to use as usize
. For example, if I use the output of Duration
using methods as_secs() = u64
or as_nanos() = u128
.
When someone passes u128::MAX
, I would like to deal with it like as usize
does by truncating the input to the max accepted value.
This is what I am trying: (https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=4a8bfa152febee9abb52d8244a5092c5)
#![allow(unused)]
use std::time::Instant;
fn format<T: Into<usize>>(number: T) {
if number == 0 {
//println!("{}", number)
} else {
//println!("{}> 0", number)
}
}
fn main() {
let now = Instant::now();
format(now.elapsed().as_nanos()); // u128
format(now.elapsed().as_secs()); // u64
}
But some of the errors I get are:
error[E0277]: the trait bound `usize: std::convert::From<i32>` is not satisfied
the trait `std::convert::From<i32>` is not implemented for `usize`
...
error[E0369]: binary operation `==` cannot be applied to type `T`
If I remove the <T: Into<size>>
it works, but I need to use as usize
.
format(now.elapsed().as_nanos() as usize);
Is there a way I could convert the input to prevent using the as usize
or how to achieve same behavior when input is just a number with no defined type?