Rust: Confusing compiler error when dealing with references to a function pointer

Created on 31 May 2018  路  1Comment  路  Source: rust-lang/rust

When using a reference to a function pointer, it gets converted to a reference to a function item instead, making future assignments require a typecast to the wanted function pointer instead.

Relevant link below:
https://play.rust-lang.org/?gist=00a013ae03ba8b50ceb37499985807f1&version=nightly&mode=debug

A-diagnostics C-enhancement T-compiler

Most helpful comment

This illustrates several diagnostic issues.

fn foo() {}

fn main() {
    let _f: fn() = foo; // Works
    let _fref: &fn() = &foo; //~ERROR expected fn pointer, found fn item
}

produces the error:

error[E0308]: mismatched types
 --> src/main.rs:5:24
  |
5 |     let _fref: &fn() = &foo; //~ERROR expected fn pointer, found fn item
  |                        ^^^^ expected fn pointer, found fn item
  |
  = note: expected type `&fn()`
             found type `&fn() {foo}`
  1. It's not clear what fn pointer or fn item are, especially for a beginner. (Arguably the term fn item is compiler jargon.)
  2. The notation fn() {foo} is meaningless unless you're already familiar with how Rust handles function types.
  3. The user is trying to take a reference to a function here. What they actually want is a function pointer (i.e. without any reference), but it can seem intuitive to take a reference to a function instead. The error message should explain what's going on, and in the ideal case suggest removing the references.

>All comments

This illustrates several diagnostic issues.

fn foo() {}

fn main() {
    let _f: fn() = foo; // Works
    let _fref: &fn() = &foo; //~ERROR expected fn pointer, found fn item
}

produces the error:

error[E0308]: mismatched types
 --> src/main.rs:5:24
  |
5 |     let _fref: &fn() = &foo; //~ERROR expected fn pointer, found fn item
  |                        ^^^^ expected fn pointer, found fn item
  |
  = note: expected type `&fn()`
             found type `&fn() {foo}`
  1. It's not clear what fn pointer or fn item are, especially for a beginner. (Arguably the term fn item is compiler jargon.)
  2. The notation fn() {foo} is meaningless unless you're already familiar with how Rust handles function types.
  3. The user is trying to take a reference to a function here. What they actually want is a function pointer (i.e. without any reference), but it can seem intuitive to take a reference to a function instead. The error message should explain what's going on, and in the ideal case suggest removing the references.
Was this page helpful?
0 / 5 - 0 ratings