Skip to content

Unboxed closures with mutable reference parameter #16652

Description

@cgaebel

It is either very hard (I don't know how to do it) or impossible to create an unboxed closure that takes a mutable reference. Here are my attempts, with the resulting error messages inline:

#![feature(unboxed_closures)]
#![feature(overloaded_calls)]

// test.rs:4:23: 4:31 error: missing lifetime specifier [E0106]
// test.rs:4 fn doit<T, F: FnOnce<(&mut int,), T>>(f: F) -> T {
//                                 ^~~~~~~~
// error: aborting due to previous error
fn doit<T, F: FnOnce<(&mut int,), T>>(f: F) -> T {
  let x = 4;
  f(&mut x,)
}

fn main() {
  let r: int = doit(|: i: &mut int| i + 1);
  println!("x = {}", r);
}

/////////////////////////////////////////////////////////////////////////

#![feature(unboxed_closures)]
#![feature(overloaded_calls)]

fn doit<'a, T, F: FnOnce<(&'a mut int,), T>>(f: F) -> T {
  let x = 4;
// test.rs:26:10: 26:11 error: `x` does not live long enough
// test.rs:26   f(&mut x,)
//                     ^
// test.rs:24:57: 27:2 note: reference must be valid for the lifetime 'a as defined on the block at 24:56...
// test.rs:24 fn doit<'a, T, F: FnOnce<(&'a mut int,), T>>(f: F) -> T {
// test.rs:25   let x = 4;
// test.rs:26   f(&mut x,)
// test.rs:27 }
// test.rs:24:57: 27:2 note: ...but borrowed value is only valid for the block at 24:56
// test.rs:24 fn doit<'a, T, F: FnOnce<(&'a mut int,), T>>(f: F) -> T {
// test.rs:25   let x = 4;
// test.rs:26   f(&mut x,)
// test.rs:27 }
// error: aborting due to previous error
  f(&mut x,)
}

fn main() {
  let r: int = doit(|: i: &mut int| *i + 1);
  println!("x = {}", r);
}

Activity

  1. japaric commented on Aug 21, 2014

    @japaric
    Contributor

    AIUI, this kind of usage requires higher-rank lifetimes, once we get that, doit would have this signature: fn doit<T, F: <'a>|: &'a mut int| -> T>(f: F), and your first attempt will work.

    If you (desperately) need this code to work right now, you can throw a mem::transmute around the &mut x in your second attempt. But that's very hacky [1], so I recommend waiting for higher-rank lifetimes.

    [1] Because 'a shouldn't appear in the generic parameter list of the doit function.

  2. aturon commented on Oct 16, 2014

    @aturon
    Contributor

    I'm going to close this as a duplicate of #17661

    Thanks for reporting it!

  3. added a commit that references this issue on Feb 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions