Closed per-oestergaard closed 1 year ago
A note — you can rely on the representation, as Month
is #[repr(u8)]
, with January being 1 and December being 12.
The reason this isn't public is because it uses NonZeroU8
and the ergonomics around nonzero types are not great. However, Month
does impl TryFrom<u8>
, so you can just do number.try_into()
and get the Result
back.
Thanks @jhpratt for the explanation.
I'll share my actual code for others to see.
So now it is -
let month : Month = number.try_into().unwrap();
or -
TryInto::<Month>::try_into(number).unwrap()
And if you do it often, you can define a trait -
trait FromNumber {
fn from_number(number: u8) -> Month;
}
impl FromNumber for Month {
fn from_number(number: u8) -> Month {
TryInto::<Month>::try_into(number).unwrap()
}
}
Month::from_number(number);
Much better :)
You can also bypass the extension trait and just use Month::try_from
:)
Thx. You are right -
Month::try_from(number).unwrap()
When I look a little back, I ended here as I did not have a simple YMD method to create a date but had to use Date::from_calendar_date(year, month, day)
where month is Month and I need a number. So I have to convert the number to Month to call from_calendar_date.
Hi. Before create like a pull request, I am curious to know why https://github.com/time-rs/time/blob/216d872e0251a0ed0bcd7cd5721a0a7bbde6fbf9/time/src/month.rs#L31 is not public outside the crate? Does anyone know the reason?
I am migrating some code from Chrono to Time. As I do not want to base my code on internal enum values, I am ending with code like this -
Not that I ever need to update it, I guess. But still it would be great to avoid it and it might not be the most efficient code.