How to compile this rust code using GATs?

182 views Asked by At

I wrote the rust code using generic associated types like below:

#![feature(generic_associated_types)]

pub trait Foo {
    type Arg<N: Clone>;
    fn foo<N: Clone>(arg: Self::Arg<N>) {
        println!("hello");
    }
}

pub fn call_foo<N: Clone, F: Foo<Arg<N> = N>>() {
    // I want to create this Box value here
    let a = Box::new(1);
    F::foo(a);
}

This code causes the following compilation error:

error[E0283]: type annotations needed
  --> core/src/utils.rs:33:5
   |
33 |     F::foo(a);
   |     ^^^^^^ cannot infer type for type parameter `N` declared on the associated function `foo`
   |
   = note: cannot satisfy `_: Clone`
note: required by a bound in `Foo::foo`
  --> core/src/utils.rs:26:15
   |
26 |     fn foo<N: Clone>(arg: Self::Arg<N>) {
   |               ^^^^^ required by this bound in `Foo::foo`
help: consider specifying the type argument in the function call
   |
33 |     F::foo::<N>(a);
   |           +++++

And when I fix the code following the help message, I got another error:

error[E0308]: mismatched types
  --> core/src/utils.rs:33:17
   |
31 | pub fn call_foo<N: Clone, F: Foo<Arg<N> = N>>() {
   |                 - this type parameter
32 |     let a = Box::new(1);
33 |     F::foo::<N>(a);
   |     ----------- ^ expected type parameter `N`, found struct `Box`
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected type parameter `N`
                      found struct `Box<{integer}>`
note: associated function defined here
  --> core/src/utils.rs:26:8
   |
26 |     fn foo<N: Clone>(arg: Self::Arg<N>) {
   |        ^^^           -----------------

F::foo::<Box<usize>>(a) also causes the same error error[E0308]: mismatched types .

Can I compile this code?

0

There are 0 answers