Ignore type parameter when type is None


I have the following function:

impl Error {
  pub fn new<S1, S2>(code: ErrorCode, message: S1, hint: Option<S2>) -> Self where S1: Into<String>, S2: Into<String> {
    Error {
      code: code,
      message: message.into(),
      hint: hint.map(|string| string.into())

This works fine except when I do the following:

Error::new(ErrorCode::Severe, "It's pretty bad.", None)

The compiler wants me to specify a type for S2 even though the type is None. Is there a better way to write this?


None is a value, not a type. So rustc wonders, “What sort of S2 isn’t this?” :slight_smile:

This matters for how Error::new is generated and called. Even though you’re only passing None in this particular case, the size of that None in the hint parameter also depends on how big Some(S2) would be.

It might be easier to have separate constructors, e.g. new and with_hint.


Just for completeness, you can use None::<String> as a value to pass a Option::None::<T> of a particular parameterization.

Type parameter defaults would let you specify a default for S2; it’s an existing unstable feature with undecided future.