In Rust, is there are map-like equivalent that stops iterating based on a condition I can choose?
I want to iterate over a vector, calling a function on each element as I do so and storing the results, but stop iterating if the function return value ever satisfies a condition
Iterative pseudo-code example:
results = []
for elem in vec:
result = foo(elem)
if result is None
break
results.push(result)
I can achieve a clumsy equivalent of this with scan by mutating the initial state but (AFAIK) it will still iterate over every element:
Rust-like pseudo-code for scan variant:
results = vec.iter().scan(false, |fail, elem|
if *fail
return None
result = foo(elem)
if result is None
*fail = true
return result
).collect()
collect() can take all the values in an Iterator 's stream and stick them into a Vec . And the map method is now generating Result<i32, &str> values, so everything lines up.
Maps are usually random through procedural generation, but there are also official pre-made maps (Hapis and Savas) and custom community maps through modding.
Press G to open up your current map once you're in a game. You can see the different biomes, roads, rivers, lakes, and Monuments. Every map is an island, and you will always spawn on the beach.
I highly recommend you choose a map between 3500 and 4000. Anything above 4000 will result in a warning shown to your players by Rust that they may not be able to play your server without performance issues. Note: The map you choose is what your players will be playing on for the duration of your wipe cycle.
results = vec.iter().map(foo).take_while(|e| e.is_some()).collect()
Iterators in Rust are lazily evaluated. In essence, the call to collect
forces each element of the iterator to be evaluated one at a time. This means that as soon as some element fails the predicate in take_while
, no further elements will be read from the initial iterator, let alone passed through map
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With