Skip to content

Add Ability for Closure to Allow Argument But Never Use It #4077

Closed
@therealgymmy

Description

@therealgymmy

I'm not sure how to phrase this properly, but basically I believe it'd be nice to see the following possible in rust.

A closure that takes in an argument, but never actually binds that argument to a name.

The reason being that in a loop, sometimes we don't actually need to know which iteration we are in. We just need to repeat a certain action for an arbitrary number of times.

For example,

// Imaginary syntax
each( [0, ..10], | :uint | {    // or maybe does not need |:uint| at all...
    doStuff(); // for 10 times

               // we don't actually need to use the element in the vector
               // Hence, really no need to assign the param a name,
               // and get a warning for not using it.
});

Essentially, argument wise, the closure will treat its argument the same way as the following C/C++ function.

int foo (uint32_t) {    // never use the param
   doStuff();
}

In C++, we could use the above function for something like this.

// Performance here is probably not nearly as good as hand-written loops,
// but that's general idea.
std::vector<uint32_t> num {1, 2, 3, 4, 5, 6};
std::for_each(num.begin(), num.end(), foo());

Alternatively, perhaps we could enhance the loop expression and allow it to take an argument to specify the number of iterations we want.

For example,

loop (until 10) {
    doStuff();
}

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