Implementing a Range Generator in Rust
Generators are a powerful tool for producing sequences of values on demand, avoiding the need to store the entire sequence in memory. This challenge asks you to implement a simple range generator in Rust, allowing you to iterate over a sequence of numbers within a specified range. This is useful for scenarios where you need to process a large number of values without allocating a large amount of memory upfront.
Problem Description
You are tasked with creating a RangeGenerator struct in Rust that generates a sequence of numbers within a given range (inclusive). The generator should implement the Iterator trait, allowing it to be used in for loops and other iterator-consuming functions. The RangeGenerator should take a start and end value as arguments during initialization. The iterator should yield numbers starting from the start value, incrementing by 1, until it reaches the end value.
Key Requirements:
- Implement the
Iteratortrait for theRangeGeneratorstruct. - The
RangeGeneratorshould store the start and end values. - The
next()method of the iterator should returnSome(value)for each number in the range, andNonewhen the end of the range is reached. - The generator should handle cases where the start value is greater than the end value gracefully (returning an empty iterator).
Expected Behavior:
The RangeGenerator should produce a sequence of integers from start to end (inclusive) when iterated over.
Edge Cases to Consider:
startequalsend: The generator should yield only thestartvalue.startis greater thanend: The generator should yield no values (an empty iterator).- Large ranges: Ensure the generator doesn't consume excessive memory.
Examples
Example 1:
Input: RangeGenerator { start: 1, end: 3 }
Output: 1, 2, 3
Explanation: The generator yields the numbers 1, 2, and 3 in sequence.
Example 2:
Input: RangeGenerator { start: 5, end: 5 }
Output: 5
Explanation: The generator yields only the number 5, as start and end are equal.
Example 3:
Input: RangeGenerator { start: 10, end: 5 }
Output: (empty iterator)
Explanation: The generator yields no values because the start value is greater than the end value.
Constraints
startandendare integers (i32).- The generator should be efficient in terms of memory usage, especially for large ranges. Avoid storing the entire range in memory.
- The generator should be able to handle both positive and negative integer ranges.
Notes
- Remember to implement the
Iteratortrait, which requires thenext()method. - Consider using a
whileloop within thenext()method to iterate through the range. - The
Option<i32>type is used to represent the result of thenext()method, indicating whether a value is available or not. - Focus on creating a clean and readable implementation. Error handling is not required for this challenge.