Using flat_map around a Result
⚓ Rust 📅 2026-03-22 👤 surdeus 👁️ 2I have some working code that's used to postprocess results from an SQL select. The general idea is that each SQL row contains zero or more UUIDs of interest, and I want to collect up all of those in one flat Vec. So this works:
fn from_row(row: Result<Row, mysql::Error>) -> Result<Vec<Self>, Error> { ... }
// Do the select and collect up the results.
let result: Result<Vec<Vec::<UuidUsage>>, _> = tx
.exec_iter(SELECT_UUIDS_SQL, params)?
.map(UuidUsage::from_row).into_iter()
.collect();
Ok(result?.into_iter().flatten().collect())
Note that this uses the map feature which can turn a Vec of Result into a Result of Vec. I'm not clear on how that really works. It does work here.
This has two .collect() calls, so it's building up all the data twice. Is it possible to use flat_map to flatten the results in one step? Tried this:
let result2: Result<Vec::<UuidUsage>, _> = tx
.exec_iter(SELECT_UUIDS_SQL, params)?
.flat_map(UuidUsage::from_row).into_iter()
.collect();
but there, the Vec of Result into a Result of Vec doesn't work. Is that something flat_map doesn't do?
error[E0277]: a value of type `Result<Vec<UuidUsage>, _>` cannot be built from an iterator over elements of type `Vec<UuidUsage>`
--> src/common/tileassetsgc.rs:80:10
|
80 | .collect();
| ^^^^^^^ value of type `Result<Vec<UuidUsage>, _>` cannot be built from `std::iter::Iterator<Item=Vec<UuidUsage>>`
|
help: the trait `FromIterator<Vec<UuidUsage>>` is not implemented for `Result<Vec<UuidUsage>, _>`
but trait `FromIterator<Result<UuidUsage, _>>` is implemented for it
--> /rustc/254b59607d4417e9dffbc307138ae5c86280fe4c/library/core/src/result.rs:2111:1
= help: for that trait implementation, expected `Result<UuidUsage, _>`, found `Vec<UuidUsage>`
note: the method call chain might not have had the expected associated types
--> src/common/tileassetsgc.rs:79:10
|
77 | let result2: Result<Vec::<UuidUsage>, _> = tx
| ____________________________________________________-
78 | | .exec_iter(SELECT_UUIDS_SQL, params)?
| |_____________________________________________- this expression has type `QueryResult<'_, '_, '_, Binary>`
79 | .flat_map(UuidUsage::from_row).into_iter()
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ----------- `Iterator::Item` remains `Vec<UuidUsage>` here
| |
| `Iterator::Item` is `Vec<UuidUsage>` here
note: required by a bound in `collect`
--> /rustc/254b59607d4417e9dffbc307138ae5c86280fe4c/library/core/src/iter/traits/iterator.rs:2015:5
Relevant previous help topic: [Solved] Flat_map and Result issue where answer is "give it up and use a FOR loop". I'm probably getting too cute with functional features here.
6 posts - 6 participants
🏷️ Rust_feed