How can I compare the result of a calculation to a generic? T is always some unsigned integer type(u64, u32, etc), so the in the snippet should work, but how can i convince the rust-compiler?
fn reproduction<T>(val: T) -> bool
where
T: PartialOrd
{
let var_of_type_integer = 7; // actually the result of a calculation
if val < var_of_type_integer { // ERROR: expected type parameter, found integer
return true;
}
false
}
The PartialOrd
trait can take a generic parameter to specify what type it can be compared against:
pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs>
where
Rhs: ?Sized,
{
// ...
}
So this compiles:
pub fn reproduction<T>(val: T) -> bool
where
T: PartialOrd<i32>,
{
let var_of_type_integer = 7;
if val < var_of_type_integer {
return true;
}
false
}
Being able to compile if of course only half of the story. When you or users actually call the function with value of some concrete type, that type has to satisfy the specified PartialOrd<i32>
trait bound.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.