Type inference failure in simple generic method call

This code wraps the reqwest::ReqwestBuilder::header<K, V> method with a function that has the same signature. Both functions have generic parameters K and V that should be easily and independently inferred from the types passed to each function.

fn set_sensitive_header<K, V>(
    builder: reqwest::RequestBuilder,
    key: K,
    value: V,
) -> reqwest::RequestBuilder
where
    http::header::HeaderName: TryFrom<K>,
    <http::header::HeaderName as TryFrom<K>>::Error: Into<http::Error>,
    http::HeaderValue: TryFrom<V>,
    <http::HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
    V: Copy
{
    match http::HeaderValue::try_from(value) {
        Ok(mut header_value) => {
            header_value.set_sensitive(true);
            builder.header(key, header_value)
            // builder.header::<K, http::HeaderValue>(key, header_value)
        }
        Err(_) => builder.header(key, value),
    }
}

This fails with:

error[E0308]: mismatched types
  --> src/lib.rs:16:33
   |
1  | fn set_sensitive_header<K, V>(
   |                            - this type parameter
...
16 |             builder.header(key, header_value)
   |                                 ^^^^^^^^^^^^ expected type parameter `V`, found struct `HeaderValue`
   |
   = note: expected type parameter `V`
                      found struct `HeaderValue`

Replacing the failing line with the following commented-out line fixes the problem.

My question:

Is this a weird failure in the compiler's type inference? The generic types K and V on the header method should be trivially inferred from the supplied parameters.

Or is there some mechanism that prefers locking the set_sensitive_header V and the header V to the same type? Perhaps through the where clauses?

I agree this seems weird.

I filed an issue for this problem: Type inference problem · Issue #95358 · rust-lang/rust · GitHub

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.