Closed
Description
Say we have a function that uses both const generics and takes an impl Trait
argument
fn const_add<const ARG: u64>(addable: impl std::ops::Add<u64>){
addable + ARG;
}
The function itself compiles just fine... but there is no way to use it.
Specifying the argument like so
const_add::<5>(10);
does not work since one cannot provide explicit arguments when impl Trait
is used [E0632]
error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
--> src/main.rs:6:17
|
6 | const_add::<5>(10);
| ^ explicit generic argument not allowed
and if we remove the explicit arguments
const_add(10);
the compiler fairly complains that it doesn't know what value to use for the const generic [E0282]
error[E0282]: type annotations needed
--> src/main.rs:6:5
|
6 | const_add(10);
| ^^^^^^^^^ cannot infer the value of const parameter `ARG` declared on the function `const_add`
Workaround: Use explicit arguments instead of impl Trait
fn const_add<A, const ARG: u64>(addable: A)
where A: std::ops::Add<u64>
{
addable + ARG;
}
and infer them with _
const_add::<_, 5>(10);
TLDR: fn
with both const
generic and impl Trait
itself compiles, but is not useable in any way. Rust Playground
Meta
Tested on both Stable 1.52.1
and Nightly 1.54.0-nightly (2021-05-18 4e3e6db011c5b482d2be)
channels, with same results.
Metadata
Metadata
Assignees
Labels
Type
Projects
Milestone
Relationships
Development
No branches or pull requests
Activity
[-]no way to use fns with both const generics and impl Traits[/-][+]No way to use `fn` with both const generics and `impl Trait`[/+]jonas-schievink commentedon May 19, 2021
This is not limited to const generics, it also happens with type generics. AFAIK this is intended behavior.
E-gy commentedon May 19, 2021
With type generics there is an actual solution - the compiler can infer the types from the context. And you can always explict types of args / return to aid the compiler in doing so.
EDIT: Okay, you can extract
impl
s into explicit generics and infer them with_
when calling the function, which works for const generics too. But this only works if you can modify the function's prototype.fn impls to explicit generics
jhpratt commentedon Aug 10, 2021
I'd just like to state that while consistent with type generics, I share the concern that it's not clear why this restriction needs to be in place. I'm refactoring some code in anticipation of using const generics soon, but I have to add a few inferred type generics for no apparent reason (they were inferred just fine as
impl Trait
before). My use case isn't something like arrays where the const generic could be inferred from usage.jonas-schievink commentedon Aug 10, 2021
This was implemented in #86176 and is now tracked in #83701
jhpratt commentedon Aug 10, 2021
Perfect! Thanks for the info.