Skip to content

Unboxed closures: ref-prefixed closures still capture by value #16814

Closed
@netvl

Description

@netvl

This code:

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

use std::cell::Cell;

fn main() {
    let test = Cell::new(5i);

    let do_something = ref |:| { println!("{}", test.get()) };

    test.set(6i);
    do_something();
    println!("{}", test.get());
}

Erroneously prints

5
6

This piece of code, which I though should be exact equivalent to the former one, works correctly, however:

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

use std::cell::Cell;

fn main() {
    let test = Cell::new(5i);

    let test_ref = &test;
    let do_something = |:| { println!("{}", test_ref.get()) };

    test.set(6i);
    do_something();
    println!("{}", test.get());
}

It prints

6
6

Looks like it copies Cell into the closure instead of taking it by reference.

Original question is on Stackoverflow

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-closuresArea: Closures (`|…| { … }`)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions