Default type parameter in Rust is weird
ZEON256
2026-09-10
rust generics
Take a look at this. I stumbled upon this when I was trying to use default type parameter and realised that you cannot have it in functions?!?!? Likewise, this example from the aforementioned link requires some weird interaction when instantiating the type
// This will be our running example for a type where all non-lifetime
// parameters have defaults:
pub enum Foo < T = String > {
Bar ( T ),
Baz ,
}
// This fails because the elided parameter desugars to an inference variable.
let foo = Foo :: Baz ;
// So this means the exact same thing:
let foo = Foo ::< _ >:: Baz ; Somehow, this issue has been around since 2022 and the discussion is on here.
In my case, I had to use it like this:
macro_rules ! sample_deserializes {
( $test_name: ident, $prefix: literal, $decode: path, $ok: pat) => {
# [ test ]
fn $test_name() {
for path in numbered_samples ( $prefix) {
let body = fs:: read ( & path)
. unwrap_or_else ( |error| panic! ( "failed to read {}: {error}" , path. display ()));
let decoded = $decode( ok_response ( & body))
. unwrap_or_else ( |error| panic! ( "decode {} failed: {error}" , path. display ()));
assert! (
matches! ( decoded, $ok),
"expected Ok variant for {}" ,
path. display ()
);
}
}
};
}
sample_deserializes! (
psi,
"psi" ,
decode_psi_response,
PsiOperationResponse :: Ok ( _)
); Somehow when using the enum, I can’t do the above and I have to do it like this:
sample_deserializes! (
psi,
"psi" ,
decode_psi_response,
PsiOperationResponse :: Ok ( _)
);