Skip to content

Associated type fails to typecheck against a reference parameter to a function (but not a function pointer or closure) #79207

Closed

Description

Rust 1.47.0-stable and 1.50.0-nightly (2020-11-18 8256379832b5ecb7f71e), both tested on the playground.

trait Example {
    type Ty;
}

impl<'a> Example for &'a i32 {
    type Ty = &'a i32;
}

fn example<F: Fn(<&i32 as Example>::Ty)>(f: F) {  }

fn main() {
    example(&|i: &i32| println!("{}", *i));
    example(|i: &i32| println!("{}", *i));

    fn print_integer(i: &i32) { println!("{}", *i); }
    example(&print_integer);
    example(*&print_integer); //fails
    example(print_integer); //fails
}

The first three calls to example succeed, but the last two calls fail with this error:

error[E0631]: type mismatch in function arguments
  --> src/main.rs:18:13
   |
9  | fn example<F: Fn(<&i32 as Example>::Ty)>(f: F) {  }
   |               ------------------------- required by this bound in `example`
...
15 |     fn print_integer(i: &i32) { println!("{}", *i); }
   |     ------------------------- found signature of `for<'r> fn(&'r i32) -> _`
...
18 |     example(print_integer); //fails
   |   

#76956 may be related.

The error does not occur if...

  • The Fn(<&i32 as Example>::Ty) bound is replaced with Fn(&i32)
  • All occurrences of &i32 are replaced with i32
  • The example function is given a lifetime parameter which is otherwise ignored:
fn example<'a, F: Fn(<&'a i32 as Example>::Ty)>(f: F) {  }
  • The generic lifetime is replaced with a generic type:
trait Example {
    type Ty;
}

impl<T> Example for Vec<T> {
    type Ty = Vec<T>;
}

fn example<F: Fn(<Vec<u8> as Example>::Ty)>(f: F) {  }

fn main() {
    example(&|v: Vec<u8>| println!("{:?}", v));
    example(|v: Vec<u8>| println!("{:?}", v));

    fn print_bytes(v: Vec<u8>) { println!("{:?}", v); }
    example(&print_bytes);
    example(*&print_bytes);
    example(print_bytes);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-typesystemArea: The type systemC-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions