← All Exercises

Rust Closures and Capture

intermediaterust~25min

Background

Closures capture their environment with flexible modes, and the move keyword forces by-value capture for ownership transfer.

Problem

Write a Rust function that creates a counter closure using move capture, returning a closure that increments and returns the count.

Input

An initial counter value.

Output

A closure that returns the current count and increments it on each call.

Sample tests

Sample 1

Input: counter starting at 0
Expected: 0, 1, 2 on successive calls

Your solution

Learning objective

Learn closure capture modes, the move keyword, Fn/FnMut/FnOnce traits, and returning closures.