Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Post History

50%
+0 −0
Q&A Rust golfing tips

Replace reduce with fold Unlike some languages, Rust's reduce returns an Option, requiring additional bytes to unwrap the output. However, Rust's fold does not. If you can find a suitable neutral...

posted 8d ago by trichoplax‭

Answer
#1: Initial revision by user avatar trichoplax‭ · 2025-04-10T22:44:42Z (8 days ago)
## Replace `reduce` with `fold`

Unlike some languages, Rust's [reduce](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.reduce) returns an `Option`, requiring additional bytes to `unwrap` the output. However, Rust's [fold](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold) does not.

If you can find a suitable neutral initial value that will keep your output the same (such as the additive identity `0` for a sum, or the multiplicative identity `1` for a product, or the empty string `""` for string concatenation), then you can use `fold` instead of `reduce`. This does not need the output to be in an `Option` because supplying an initial value means there is no doubt over what the output should be for an empty input[^1], so `fold` returns the output directly.

```rust
println!("{}",(1..6).reduce(|a,b|a*b).unwrap());  // 120
println!("{}",(1..6).fold(1,|a,b|a*b));           // 120
```

[Test both on Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=893954d3331f064003a0e047625dc581)


[^1]: The output that makes sense for an empty input will differ depending on the operation being carried out. The sum of an empty list of numbers is 0, but the product of an empty list of numbers is 1. Since `reduce` accepts an arbitrary function as the operation, and Rust cannot know what the appropriate output for an empty input would be for all functions, it returns `None` for an empty input.