Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow coercing non-capturing closures to function pointers #1555

Closed
archshift opened this issue Mar 23, 2016 · 3 comments · Fixed by #1558
Closed

Allow coercing non-capturing closures to function pointers #1555

archshift opened this issue Mar 23, 2016 · 3 comments · Fixed by #1558
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.

Comments

@archshift
Copy link
Contributor

In C++, you are able to pass a non-capturing lambda as a function pointer, as, for example, a function argument:

void foo(void (*foobar)(void)) {
    // impl
}
void bar() {
    foo([]() { /* do something */ });
}

It would be incredibly convenient for rust to be able to do the same:

fn foo(foobar: fn()) {
    // impl
}
fn bar() {
    foo(|| { /* do something */ });
}

A use case would be a static (const) array of function pointers, where dynamic dispatch is not necessary.
Example in current rust (this is a compilable example):

extern {
  static mut b: u32;
  static n: usize;
}

const a: [&'static Fn(); 4] = [
  &|| unsafe { b = 4 },
  &|| unsafe { b = 2 },
  &|| unsafe { b = 3 },
  &|| unsafe { b = 1 },
];

pub fn main() {
  if n < 4 {
    a[n]();
  }
}

This obviously relies upon dynamic dispatch to a level that rust is unable to optimize away. Ideally it would be possible to use a table of fn()s instead of &'static Fn() and rust would be able to coerce the closures into function pointers because nothing needs to be captured.

Another, possibly more widely-applicable scenario is simply being able to pass a closure into a C function that takes a callback.

See previous discussion at rust-lang/rust#32449.

@archshift
Copy link
Contributor Author

Created RFC at #1558.

@nrc nrc added the T-lang Relevant to the language team, which will review and decide on the RFC. label Aug 18, 2016
@JoeyAcc
Copy link

JoeyAcc commented May 11, 2017

What's the status on this? I ask because on the one hand this issue is closed, yet on the other the feature is still gated behind feature(closure_to_fn_coercion).

@eddyb
Copy link
Member

eddyb commented May 11, 2017

@JoeyAcc You want to look at the tracking issue (rust-lang/rust#39817).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-lang Relevant to the language team, which will review and decide on the RFC.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants