3 ms·
The Kotlin compiler can handle chains of potentially().nullable()?.invocations(). Is the Rust early-error returning not a similar case, or am I missing somethin
by MrBuddyCasino 4y ago
The Kotlin compiler can handle chains of potentially().nullable()?.invocations(). Is the Rust early-error returning not a similar case, or am I missing something?
- gpm 4y agoRust does the same.
- NoraCodes 4y agoYeah, 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.
- cormacrelf 4y agoKotlin and also C# ? operators only “return” from the expression being evaluated. Most documentation says “return” a bit ambiguously but that’s what they mean. AFAIK Rust is the first language to use ? in such a way as to return from a function, and that’s quite different. Kotlin ? can technically be emulated in Rust with an IIFE (immediately invoked function expression) like so: // never do this, it’s rude let x = (|| potentially().nullable()?.invocations())(); Or with Option::map, and_then and friends: // this is the way let x = potentially().nullable().map(|y| y.invocations());
- MrBuddyCasino 4y agoThat made it click, thanks!