rust-lang / rust-lang/rfcs

Sugar for closures with restricted access to enclosing's names.

Open
#2,496 9 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

T-lang
Dominant language
Markdown
Stars
6.6k
Forks
1.7k
Avg merge
16h 14m
Merged PRs (30d)
1

Description

If I am writing a long function, I often want to close off a chunk of code with { code_in_here } so that local variables I declare within the chunk don't "escape". Example:

fn long_function() {
   let mut x = 1;
   let y = 3
   {
      let y = 2;
      println!("I have {} apples");
   }
   assert!(y == 3);
}

However, inside the { }, it's still possible to read (and even write to) x. When reading long functions, I would like a way of assuring that a given complicated chunk of code only touches the variables I want it to touch.

A solution:

fn long_function() {
   let x = 1;
   let y = 3
   {fn t(x: &i32) { 
      let y = 5;
      println!("I have {} apple and {} oranges.", x, y);
   }t(&x);}
   assert!(y == 3);
}

This works, and does exactly what I need, but is rather ugly. I suggest a bit of built-in sugar for this use case. Perhaps rather than:

{fn t(args: &T, to: &mut U, pass: &V) { 
   //isolated logic
}t(&args, &mut to, &pass);}

we would have:

close (&args, &mut to, &pass) {
   // enclosed logic, assured not to touch anything but args, to and pass
}

And we can tell just by looking at one line exactly what variables this chunk of code touches and what its side effects are.

...or even better, a closure with controlled access to its enclosing scope that returns a value:

let a: i32 = close (&args, &mut to, &pass) -> i32 {
   // enclosed logic, assured not to touch anything but args, to and pass
   to = args + pass;
   let some_int = 5 - args;
   some_int
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The issue does not name implementation files or tests; start by reviewing its closure-scope examples and the repository's RFC process. Compare the proposed syntax and alternatives, then define the semantics and determine whether the proposal is ready for an accepted RFC.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.