I have a function that gets the dimensions of an image, and in different scenarios, I would it to be cast from a u32
to another number type suchas usize
, i32
, etc. However, when I try to do the following in get_dimensions
it doesn’t work. Is something like this possible? I looked at How do I convert between numeric types safely and idiomatically? but in that example it uses an explicit type such as i32::from(...)
whereas I would hopefully like to use a dynamic type.
Rust Playground Example
struct Example {
width: u32,
height: u32
}
impl Example {
pub fn get_dimensions<T>(&self) -> (T, T)
where
T: From<u32>,
{
(T::from(self.width), T::from(self.height))
}
}
pub fn main() {
let example = Example { width: 800, height: 600 };
let dimensions = example.get_dimensions::<usize>();
println!("{dimensions}");
}
The error message I receive:
the trait bound `usize: From<u32>` is not satisfied
the following other types implement trait `From<T>`:
`usize` implements `From<bool>`
`usize` implements `From<std::ptr::Alignment>`
`usize` implements `From<u16>`
`usize` implements `From<u8>`
1