Here the compiler will reject the program, because it cannot monomorphize the impl RangeBounds, because it has no type information to go on. In reality, I don't care what type the compiler chooses for the Some case, because it is never instantiated. What I would really like is for the compiler to choose something like !, the never type. Is there a way to do this, without having to write type annotations with a made up type (most likely ())?
Then what's the point of making it an Option (and an argument at all)? Aren't you just trying to specify a type parameter for the function, like fn parse_int<R>(input: Input) -> Output?
I think what they're saying is that, in the case where they pass None, their code doesn't care what the type of range is, so it seems awkward that they have to specify it.
For example:
use std::fmt::Display;
fn example<T: Display>(o: Option<T>) {
match o {
Some(value) => println!("{}", value),
None => {}
}
}
fn main() {
// Works, because the compiler knows T is &str
example(Some("test"));
// Doesn't work, because the compiler doesn't know what T is -
// but T is never used in this code branch!
example(None);
}
Change your API to have separate parse_int and parse_int_with_range methods; the first can just call the second with the necessary type annotations
Add a helper method that returns a suitable Option::<T>::None, so users can e.g. call parse_int(input, no_bounds())
Have parse_int receive impl RangeBounds<i32> directly instead of an Option, if an unbounded range would have the same behavior/meaning as passing None for your application. Then, you can just call parse_int(i, ..). (Related: there's a style question of whether it would be clear to readers at the call site why the function is receiving a ..)
One thing, which i might do is just stick a type declaration on it in a const and then at least you don't have to repeat the type decl,
the following added to your example works.
It is possible to qualify None in this case with a variety of methods. Considering the trait bound Display in the provided example, any of these will work:
Consequently the Box<dyn Trait> approach also works for the case given in the OP, assuming Box<dyn RangeBounds<T>> implements RangeBounds<T>: playground