4 ms·
Yeah, Rust does that as well. The issue the author is talking about here is that when you write a closure: fn foo(inputs: &[Input]) -> Result<Vec<Output>,
by NoraCodes 4y ago
Yeah, Rust does that as well. The issue the author is talking about here is that when you write a closure:
fn foo(inputs: &[Input]) -> Result<Vec<Output>, Error> {
inputs
.iter()
.map(|input| { input.something_fallible()? })
.collect()
}
that ? is an early return from the closure, not foo. The correct way to do this is:
fn foo(inputs: &[Input]) -> Result<Vec<Output>, Error> {
inputs
.iter()
.map(|input| { input.something_fallible() })
.collect::<Result<Vec<Output>, Error>>()
}
ref: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- MrBuddyCasino 4y agoI wonder how come the type must be specified explicitly as "collect::<Result<Vec<Output>, Error>>()" and can't be inferred, given that the function return type is already spelled out as "Result<Vec<Output>, Error>"? Is there a specialisation for collect() for Result<> types that has to be explicitly triggered?
- gpm 4y agoIt doesn't have to be specified explicitly in this case, it can be inferred. https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7bf4c01c6cfe0a2b200d9a4f5133860e https://play.rust-lang.org/?version=stable&mode=debug&editio... Probably just habit from GP to write out the return type, since collect so often can't be inferred. Or maybe to make it easier to change it to an intermediate value which you use ? with (at which point the type can no longer be inferred). https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=3b4b8cf497b8cdc31a479d40b4b0b72f https://play.rust-lang.org/?version=stable&mode=debug&editio...
- NoraCodes 4y agoYeah, apologies, that's just habit on my part.