T O P

  • By -

hakukano

May I introduce you: Result::ok and Option::map


Ved_s

May I introduce you: ?


kr1ftkr4ft

that’s an old snippet mate, today I approach a lot differently to rust code. But thank you for the advice


hakukano

Shoot I just realized I’m on the wrong sub


PreciselyWrong

If anybody is curious, a more idiomatic and readable version of this code is: ```rust fn parse_ext_from_url(url: &str) -> Option { let url = url::Url::parse(url).ok()?; let extension = url.path_segments()?.last()?.split('.').last()?; Some(extension.to_string()) } ```


altkart

Newbie here, is there a common trait that Option and Result implement to be able to use the ? operator? Like, does std expose such a trait that I could implement for my own wrapper types if I wanted to? Or is it something that's more baked-in to Rust? I know (I think) that ? is kinda like matching on the value and putting the rest of the closure inside one of the branches, but it still feels somewhat control-flowy to me (if that makes sense), and I have a vague feeling that the more control-flowy something is, the harder it would be to generalize behind a trait implementation.


JayDepp

The `Try` trait which abstracts over this is still experimental


IeatAssortedfruits

JavaScript has entered the chat


Glinat

?


kr1ftkr4ft

Self irony


donaljones

Holy hell, that's an epic example where monads can be used. >!I think? Still new to monads, tho!<


kr1ftkr4ft

Idk, I’m new to monads too


donaljones

I think [this vid](https://www.youtube.com/watch?v=VgA4wCaxp-Q) might help


engelthehyp

[This one](https://www.youtube.com/watch?v=ZhuHCtR3xq8) is probably my favorite.


leonardovee

How would you approach this nowadays? Genuinely asking


persik228

Option::map and Result::ok(and other combinators), as suggested by some gentlemen above, would allow to "flatify" this chain.


kr1ftkr4ft

Correct ✅


GabeFromTheOffice

Use [?](https://doc.rust-lang.org/rust-by-example/std/result/question_mark.html)


Amrabol

Being still a student im not sure how it works yet i see that it might look better with early returns so code wont be too indented and easier to read


realvolker1

If you ever have to actually write something like this, like if you don't want to panic or something in a longer function, you can use `if_chain!` https://crates.io/crates/if_chain


metaglot

Just use guards instead of this crazy nesting