You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
where I want to implement From for &T types. Could you give me any suggestions?
Below is my complete solution. I also write a macro solution for From traits.
// TODO: Define a new `SaturatingU16` type.// It should hold a `u16` value.// It should provide conversions from `u16`, `u8`, `&u16` and `&u8`.// It should support addition with a right-hand side of type// SaturatingU16, u16, &u16, and &SaturatingU16. Addition should saturate at the// maximum value for `u16`.// It should be possible to compare it with another `SaturatingU16` or a `u16`.// It should be possible to print its debug representation.//// Tests are located in the `tests` folder—pay attention to the visibility of your types and methods.use std::ops::Add;use num::Unsigned;traitIntoU16<T>{fninto_u16(self) -> u16;}implIntoU16<SaturatingU16>forSaturatingU16{fninto_u16(self) -> u16{self.value}}impl<'a>IntoU16<&'a SaturatingU16>for&'a SaturatingU16{fninto_u16(self) -> u16{self.value}}impl<T>IntoU16<T>forTwhereT:Unsigned + Into<u16>,{fninto_u16(self) -> u16{self.into()}}impl<'a,T>IntoU16<T>for&'a TwhereT:Unsigned + Into<u16> + Copy,{fninto_u16(self) -> u16{(*self).into()}}#[derive(Debug,Clone,Copy)]pubstructSaturatingU16{value:u16}impl<T:Unsigned + Into<u16>>From<T>forSaturatingU16{fnfrom(value:T) -> Self{Self{value: value.into()}}}impl<'a,T:Unsigned + Into<u16> + Copy>From<&'a T>forSaturatingU16{fnfrom(value:&'a T) -> Self{Self{value:(*value).into()}}}// macro_rules! impl_from {// ($t:ty) => {// impl From<$t> for SaturatingU16 {// fn from(value: $t) -> Self {// SaturatingU16 {// value: value.into(),// }// }// }// impl<'a> From<&'a $t> for SaturatingU16 {// fn from(value: &'a $t) -> Self {// SaturatingU16 {// value: (*value).into(),// }// }// }// };// }// impl_from!(u8);// impl_from!(u16);impl<T>Add<T>forSaturatingU16whereT:IntoU16<T>,{typeOutput = SaturatingU16;fnadd(self,rhs:T) -> Self::Output{let rhs_value:u16 = rhs.into_u16();let new_value = self.value.saturating_add(rhs_value);SaturatingU16{value: new_value}}}impl<T>PartialEq<T>forSaturatingU16whereT:IntoU16<T> + Copy,{fneq(&self,other:&T) -> bool{self.value == other.into_u16()}}
The text was updated successfully, but these errors were encountered:
I want to write an minimal solution to reduce duplications.
Everything is good except this part:
where I want to implement From for &T types. Could you give me any suggestions?
Below is my complete solution. I also write a macro solution for From traits.
The text was updated successfully, but these errors were encountered: