Oliver Jumpertz
Oliver Jumpertz
  • 15
  • 67 952
This is my favorite feature in Rust
This is my favorite feature in Rust, Extension Traits! If you don't know them, yet, or want to learn more, this video is for you. Enjoy!
---
📝 My blog 📝 Read at oliverjumpertz.com/
มุมมอง: 8 808

วีดีโอ

You're probably misusing unwrap in Rust...let's fix that
มุมมอง 5Kหลายเดือนก่อน
Here's a very important thing about undesirable state (or errors) in Rust: They still happen, and Rust even has escape hatches (for good reason). That means: You still have to put in some thought to handle them. Gladly, there are a few rules you can follow to get the best experience out of the language when dealing with errors. Ready to learn a little more? Let's go! Timestamps: 00:00 Intro 00...
The US Government wants to try to replace all C with Rust
มุมมอง 2.9K3 หลายเดือนก่อน
So, this is still relatively fresh, but the US government, or better DARPA, wants to try to replace a lot of legacy C/C code with Rust. This will probably also affect future projects as DARPA explicitly states that they don't think that C or C are safe enough (or can be programmed in a safe enough way) to circumvent all the usual security vulnerabilities. They aim at creating an automated solut...
Rust's Operator Overloading actually makes sense
มุมมอง 4.4K3 หลายเดือนก่อน
Operators are a pretty interesting concept. On one hand, they can improve our lives a lot. On the other hand, they can also worsen a lot. Rust, however, uses a pretty solid concept to deal with operators and their overloading, and it's probably about time to learn a little more about them. Let's dive into what operators are, how they are usually used in programming, how Rust handles them, and w...
Why It (Mostly) Doesn't Matter How You Code In Rust
มุมมอง 15K5 หลายเดือนก่อน
Have you ever wondered whether the code you write is really the optimal solution, or can't you stop thinking about performance? Well, as it turns out, Rust is one of the languages that helps you a lot in exactly these areas. Why worry about HOW you WRITE code if you can instead focus on HOW to SOLVE your problems? Let's find out what Rust does for us and how it does it. This video is, of course...
You Should Really Know These Traits in Rust
มุมมอง 16K8 หลายเดือนก่อน
Although Rust's standard library is pretty small compared to other languages, it comes with most of the batteries included. It even standardizes conversions with a few important traits that any Rust developer should know about. So, what better to do than to take a look at these traits, learn about them, and get you ready to master conversions in Rust?! Timestamps: 00:00 Intro 00:46 From and In...
How To Create Your Own Link Shortener In Rust (beginner-friendly project)
มุมมอง 4.3K9 หลายเดือนก่อน
You probably know tools like Bitly, t.ly, TinyURL, and many more. They are all link (or URL) shorteners, but did you know that their core logic isn't that difficult to implement yourself? What if you could create your very own link shortener, in Rust, as a perfect learning project and one that actually provides yourself some value? This is what this video is about. We implement our very own lin...
Is this IDE the next big thing for Rust?!
มุมมอง 635ปีที่แล้ว
There is a new Rust IDE in town...and it's developed by JetBrains. Yes, the company that already develops several IDEs like IntelliJ Idea, WebStorm, and more, has just released a new Early Access Preview of their dedicated Rust IDE. Join me when I take a look at it and see what it got to offer! Timestamps: 00:00 Intro 01:07: How to get RustRover 01:45: Overall look and general functionality 02:...
Rust has an advantage you haven't realized yet
มุมมอง 2Kปีที่แล้ว
Rust has an advantage you haven't realized yet. It's its ecosystem. Rust is opinionated and provides many tools itself. Tools that other languages don't provide and let their community work on. When you work with Rust, you get it all from the language's maintainers and thus get an incredible developer experience, which is a pleasure to work with. The whole ecosystem is deeply integrated and doe...
I Built my Own Reverse Proxy...and (D)DoS'd Google
มุมมอง 908ปีที่แล้ว
My good friend Simon Høiberg recently challenged me to build my own custom domain reverse proxy, and I could not resist. This is when I went down the rabbit hole to implement a simple custom domain reverse proxy in Rust. When I tested this little monster, I accidentally (D)DoS'd Google (let's be honest, it wasn't distributed...but hey...we could still try in the future...jk!), but other than th...
How Discord Stores Trillions Of Messages
มุมมอง 1Kปีที่แล้ว
Discord stores and works with TRILLIONS of messages nowadays. They recently released a blog post talking about how they handle all these messages and what they had to go through to get their system stable. In this video, we go over what they do, and additionally try to recreate their data services, so you can do the same in the future. Timestamps: 00:00 Intro 00:27 Discord and Previous Architec...
Rust's Option In 180 Seconds
มุมมอง 960ปีที่แล้ว
Rust has no null but a pretty genius type, called Option, that makes working with absent data explicit and a great experience. Learn everything you really need to know about Rust's Option in 180 seconds! Timestamps: 00:00 Intro 00:15 Programming and null 00:39 Rust's Option 01:44 How to work with Option in Rust 02:46 Option and memory usage 03:06 Outro Resources for further reading: doc.rust-la...
Rust's Enums In 180 Seconds
มุมมอง 968ปีที่แล้ว
Rust's Enums explained in 180 seconds - as short as possible. Did you know that Rust's Enums are actually quite powerful and combine the features of enums from many other languages? You can even nest data inside them, and even better, each member type can have a different structure. Timestamps: 00:00 Intro 00:16 Rust's Enums compared to TypeScript's 00:39 Features 02:08 Memory 02:51 Outro Some ...
How to Read Data from Files in Rust
มุมมอง 2.7Kปีที่แล้ว
Five idiomatic ways to read data from files in Rust Timestamps: 00:00 Intro 00:48 Reading an entire File into a String - Code 01:13 Reading an entire File into a String - Advantages and Disadvantages 01:52 Reading an entire File into a Byte Vector - Code 02:32 Reading an entire File into a Byte Vector - Advantages and Disadvantages 03:00 Reading a File Line by Line - Code 03:44 Reading a File L...
How to Write Data to Files in Rust
มุมมอง 2.2Kปีที่แล้ว
Learn How to Write Data to Files in Rust. Timestamps: 00:00 Intro 00:51 Writing all Data to a File at Once - Code 01:47 Writing all Data to a File at Once - Advantages and Disadvantages 02:18 Writing all Data to a File at Once with the fs::File API - Code 03:22 Writing all Data to a File at Once with the fs::File API - Advantages and Disadvantages 03:57 Appending Data to a File - Code 04:51 App...

ความคิดเห็น

  • @CalifornianViking
    @CalifornianViking 14 ชั่วโมงที่ผ่านมา

    Excellent. Some of these concepts seem very abstract, but you explain them i a practical way.

  • @returncode0000
    @returncode0000 3 วันที่ผ่านมา

    Oh, this was awesome, your teaching style is superb, also very interesting topic. I think knowing how to implement traits is probably the most important topic in rust, also higher order trait bounds 🙂

    • @oliverjumpertzme
      @oliverjumpertzme 3 วันที่ผ่านมา

      Thank you really much! 💛

  • @mikymuky1171
    @mikymuky1171 5 วันที่ผ่านมา

    This made me LOVE rust! So aesthetically pleasing. Also axum and sqlx are bringing a new air of glory to backend for me. I was getting tired of python's libraries xD

  • @pookiepats
    @pookiepats 6 วันที่ผ่านมา

    Swift Protocols ❤ cool thatRust has a more flexible unsafe version

  • @ИванРагозин-я8я
    @ИванРагозин-я8я 6 วันที่ผ่านมา

    more Rust videos, bro.

  • @doyinawosanya17
    @doyinawosanya17 6 วันที่ผ่านมา

    This trait could also easily be made generic over all IntoIterator implementers

  • @TeamDman
    @TeamDman 6 วันที่ผ่านมา

    Great video! I'd love a video on Tower from you given your praise for it, I want to know more :o

    • @oliverjumpertzme
      @oliverjumpertzme 6 วันที่ผ่านมา

      Definitely noted, thanks! 😁🙌🏻

  • @Shaunmcdonogh-shaunsurfing
    @Shaunmcdonogh-shaunsurfing 6 วันที่ผ่านมา

    Very nicely illustrated. Big fan of Rust too.

    • @oliverjumpertzme
      @oliverjumpertzme 6 วันที่ผ่านมา

      Thanks a lot! And hey there fellow Rustacean! 🙌🏻

  • @khai96x
    @khai96x 7 วันที่ผ่านมา

    I have written an extension trait called `pipe_trait::PipeTrait` that provides `.pipe()` method which allows you to call regular functions in a dot chain. Using it would reduce boilerplate compared to defining all the custom extension traits.

    • @oliverjumpertzme
      @oliverjumpertzme 7 วันที่ผ่านมา

      Oh, that's nice! Anything to share like a crates.io link? ☺️

  • @Tsunami14
    @Tsunami14 7 วันที่ผ่านมา

    C# Extension Methods says hi.

    • @Tsunami14
      @Tsunami14 7 วันที่ผ่านมา

      Not throwing shade at Rust. Extension methods have been a great addition to the C# language, so I'm glad to see it as part of the Rust ecosystem as well. ...now if only we could get Rust-style enums. (discriminated unions?)

  • @brutetriple8637
    @brutetriple8637 7 วันที่ผ่านมา

    btw using a reference to a vector as an function argument is bad in Rust. it means the caller have the own a Vec in order to use this function. this is an unnecessary limitation. the function should has a `&[i32]` slice as an argument, so it can accept arrays and Vecs as arguments, because both types are easily converted into a slice.

    • @oliverjumpertzme
      @oliverjumpertzme 7 วันที่ผ่านมา

      True in production code. Just made it explicit here to showcase the general concept. ☺️

  • @denizsincar29
    @denizsincar29 7 วันที่ผ่านมา

    Bist du deutsch? Your vids are great btw

    • @oliverjumpertzme
      @oliverjumpertzme 7 วันที่ผ่านมา

      Ja. ☺️ Dankesehr!

    • @denizsincar29
      @denizsincar29 7 วันที่ผ่านมา

      @ Hast du deutsch kanal? Ich will deutsch und rust praktiken at the same time))

    • @oliverjumpertzme
      @oliverjumpertzme 7 วันที่ผ่านมา

      @ im moment noch keinen deutschen Kanal, sorry. ☺️

  • @anon_y_mousse
    @anon_y_mousse 7 วันที่ผ่านมา

    This brings up a good point about what's wrong with most languages' operator overloading designs. Order matters, even when operations are commutative. What we need is a way to define operators where order doesn't matter because the operation itself is commutative anyway. I'm not sure what syntax that would take on, but hopefully the collective unconscious will bring some sort of proposal to the forefront. It sounds loony, but trust me, it's a thing, I've seen it work far too often to believe otherwise.

  • @anon_y_mousse
    @anon_y_mousse 7 วันที่ผ่านมา

    Personally, I hate method chaining. And I don't agree that selective module loading has to be limited to whole modules and indeed a good linker will allow you to have dependency chains documented so only what is truly necessary gets included. However, you've missed a step. Rust has a feature, and apparently has for a few years now, that allows you to designate a "friend class" like C++ does. You can do `pub (in crate::foo)` to make something visible to another module. Of course, I hate the way pub limits you to a single item. I'd love it if they changed it to allow using braces to enclose a whole slew of things you want made public.

    • @RustIsWinning
      @RustIsWinning 6 วันที่ผ่านมา

      Cannot take someone serious who(writes(this(unreadable(mess(lmao))))) 😂

    • @anon_y_mousse
      @anon_y_mousse 6 วันที่ผ่านมา

      @@RustIsWinning That's still method chaining.

    • @RustIsWinning
      @RustIsWinning 5 วันที่ผ่านมา

      @@anon_y_mousse Fair point. At least I looked it up and found method cascading which I have never seen before. Learned something new today lol

  • @Dygear
    @Dygear 7 วันที่ผ่านมา

    Very well done, walked me down the rose path and then shows me why all roses have thorns. Very well done.

  • @johnmph7562
    @johnmph7562 8 วันที่ผ่านมา

    It exists in Objective-C also

  • @softwaresirppi
    @softwaresirppi 8 วันที่ผ่านมา

    Dart has had this for years. It's called extension methods

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      True, Kotlin also has it, with their extension methods. ☺️

  • @Hellbending
    @Hellbending 8 วันที่ผ่านมา

    Another gigachad-gigabrain level video from the man himself! Loveee your videos on traits, even when I’m accustomed to using them there’s always a nugget of information somewhere, thanks bro 🤙❤️

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      Thanks a lot and super glad you like it! 😁🙌🏻

  • @taquanminhlong
    @taquanminhlong 8 วันที่ผ่านมา

    3:12 wrapper should have lifetimes to borrow Vec 😂

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      Sure, in reality, a good idea. Probably not necessary to explain the concept. ☺️

  • @gideonunger7284
    @gideonunger7284 8 วันที่ผ่านมา

    extension traits suck and its basically an ugly hack. traits are open concepts so any other crate can now also implement those extension functions which might or might not make any sense.

    • @Cm0nd00d
      @Cm0nd00d 8 วันที่ผ่านมา

      boo

    • @norlock
      @norlock 8 วันที่ผ่านมา

      False that's only possible if you re-export the trait from the source library.

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      The import is always explicit ☺️

    • @gideonunger7284
      @gideonunger7284 8 วันที่ผ่านมา

      @@oliverjumpertzme so? thats not what im talking about at all.

    • @gideonunger7284
      @gideonunger7284 8 วันที่ผ่านมา

      @@Cm0nd00d you can boo me but im right. not everything rust does is per definition good. i write a ton of rust and some parts of it are just shit and some design decisions are baffling and bad.

  • @ZaraUTech
    @ZaraUTech 8 วันที่ผ่านมา

    11:30 ❤

  • @Anomaa
    @Anomaa 8 วันที่ผ่านมา

    Well... this feature is present in a good part of languages, but with a simpler syntax. That's why I never managed to get into Rust. Ok it's a very secure and fast language. But on the other hand doing simple things like extending a type becomes more of a "trick" than anything else, which is not necessarily very intuitive at first glance. For the moment, the trade off doesn't suit me, I don't develop ultra serious stuff that must be 99% secure and performant.

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      Would you care to explain? C++ only has abstract classes and inheritance, Java requires you to implement any interface at the class declaration level and has inheritance, Kotlin has extension functions, which work similarly to Rust and inheritance, JavaScript only has the global prototype, TypeScript as well, Go only has promoted structs, so...I'd love to hear your thoughts on this. ☺️

    • @Anomaa
      @Anomaa 8 วันที่ผ่านมา

      @oliverjumpertzme I found this wikipedia page, even though it doesn't seem very... sourced. en.m.wikipedia.org/wiki/Extension_method. But the idea is that either it's dynamic, or there's a keyword like "extension" that makes it much more readable. Or for more function-oriented languages like common lisp or Julia it's as simple as writing a function, like you did in the video, because there is not the alternative of the dot syntax. I probably exaggerated on the "good part", but my basic idea is that, even if I can understand the beauty of having everything come from the same concept like traits, it can make things harder to read and understand. For me personally it demotivates me from seriously trying the language.

    • @Anomaa
      @Anomaa 8 วันที่ผ่านมา

      @@oliverjumpertzme I found this wiki page, even though it doesn't seem very... sourced. en.m.wikipedia.org/wiki/Extension_method But the idea is that either it's dynamic, or there's a keyword like "extension" that makes it much more readable. Or for more function-oriented languages ​​like common lisp or Julia it's as simple as writing a function (exactly like the alternative in the video, but in those languages ​​it automatically becomes methods). I probably exaggerated on the "good part". My basic idea is that, even if I can understand the beauty of having everything come from the same concept like traits, it can make things harder to read and understand. For me personally it demotivates me from seriously trying the language.

    • @JustATempest
      @JustATempest 7 วันที่ผ่านมา

      @@oliverjumpertzme He might be thinking of C sharp.

  • @JorgetePanete
    @JorgetePanete 8 วันที่ผ่านมา

    3:46 Why is there a line going from "can implement" to "can't implement"?

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      I have watched my video over and over again to find issues…and you directly find one. Damn. That's definitely a mistake. There shouldn't be an arrow. 😅

    • @JorgetePanete
      @JorgetePanete 8 วันที่ผ่านมา

      @oliverjumpertzme 😂 It happens to the best of us, for me it's useful to let a few hours pass before I look at something again and the errors jump at me.

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      @ guess what, I did that for several days. 😂

  • @bhavyakukkar
    @bhavyakukkar 9 วันที่ผ่านมา

    your videos are so nicely planned and executed

    • @oliverjumpertzme
      @oliverjumpertzme 8 วันที่ผ่านมา

      Thank you! 💛 super glad you like it 🙌🏻

  • @RenderingUser
    @RenderingUser 9 วันที่ผ่านมา

    How are your vidoes made btw? the visuals specifically

    • @oliverjumpertzme
      @oliverjumpertzme 9 วันที่ผ่านมา

      Hey, I use Davinci Resolve and basically just keyframe-animate images. For the code snippets, I use Snappify. ☺️ does this help?

  • @qbasic16
    @qbasic16 9 วันที่ผ่านมา

    Thank you! I love extension traits and Rust in general :)

  • @OfficialViper
    @OfficialViper 9 วันที่ผ่านมา

    Best Rust TH-camr uploaded again, the day is saved

  • @rpitit
    @rpitit 9 วันที่ผ่านมา

    Extension traits are a neat feature, but so are traits in Rust in general. Currently doing a lot of async programming, I also love that RPITITs have finally been stabilized.

    • @oliverjumpertzme
      @oliverjumpertzme 9 วันที่ผ่านมา

      Yep! I was looking forward to those so much. Super happy they are finally here 💛

    • @OfficialViper
      @OfficialViper 9 วันที่ผ่านมา

      If you like traits and async, check out the async_trait crate :D Didn't know about it and had a lot of boiletplate code in my project. That crate is true magic.

  • @jaw_develops
    @jaw_develops 19 วันที่ผ่านมา

    Omg what a great content, thanks for your effort!!!!

  • @milacc0000
    @milacc0000 หลายเดือนก่อน

    Just for my satisfaction, TryFrom example can be perttified by collect `split` variable first and just use single `if split.len() != 2 { return ... }` statement. If there is no split target in given string, it just collect into vector with single element.

  • @julietlukasunny5651
    @julietlukasunny5651 หลายเดือนก่อน

    Do you have source for learning this

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Phew, many, to be honest. But the best training is probably building something yourself, learning along the way by googling yourself through any issue you encounter. :)

    • @julietlukasunny5651
      @julietlukasunny5651 หลายเดือนก่อน

      @@oliverjumpertzme Thanks for the tip! I totally agree sometimes the best way to learn is just diving in and figuring things out as you go. If you don't mind, could you share the source as well

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      @@julietlukasunny5651which source exactly do you mean? If you don't mind me asking. 😅

  • @ntippy
    @ntippy หลายเดือนก่อน

    Excellent as always. If you are ever in St Louis we would love to have you at the STL Rust Meetup.

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Hey, thanks a lot! Oh, if I ever make it to St. Louis, I'll remember that! 💛

  • @matthiskalble3621
    @matthiskalble3621 หลายเดือนก่อน

    There are situations where you have constraints where unwrap is save as you have guaranteed ok or some value

    • @matthiskalble3621
      @matthiskalble3621 หลายเดือนก่อน

      Due to API constraints. Except is still nicer tho

  • @petrusion2827
    @petrusion2827 หลายเดือนก่อน

    It would be awesome if you could make a sequel to this video about Borrow, Deref, ToOwned and Cow.

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Thanks! And absolutely noted as an idea! 💛

  • @aspiring_millionaire
    @aspiring_millionaire หลายเดือนก่อน

    Super helpful! Thanks Oliver I have a question though, I use axum framework at work and almost all of my endpoint handler functions return the error type in Response<Body>, I use the Response::builder() function to usually convert the error response into my desired HTTP response like 400, 403 or 500 etc My question to you is, as per the docs it has the unwrap() function at the end, how can I possibly handle the errors in this case, especially considering the fact that I want to do it gracefully and not just use .expect() cause it looks like a shortcut What is the general convention for handling the unwrap() which are in the docs for all the libraries we use?

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Hey, thanks a lot! 💛 Regarding your question: I think we need to distinguish between errors and bugs here ( once again :) ). The question, thus, is: Is your response not building correctly a real bug or something you should expect and handle? First of all, I'd make sure that your route handler either returns a Result<Response, SomeError> or something like Result<Response, (StatusCode, String)> (because the latter can easily be converted to a valid response by axum's buit-in converters). If you return a non-dynamic response, i.e. no dynamic contents or just little, mostly statically defined in your source code, I'd still use expect because if that Response doesn't build, that's a real bug. An example of the sole return statement of a handler function: Ok(Response::builder() .status(StatusCode::TEMPORARY_REDIRECT) .header("Location", "example.com/redirect-url".into()) .body(Body::empty()) .expect("This response should always be constructable")) There is nothing really dynamic in this response and building that should not fail if you do everything correctly. Or let's say: If something fails, that's a bug. If you have a highly dynamic response that you can't really control, I'd map to an internal server error, like so: Ok(Response::builder() . status(StatusCode::OK) .header("Cache-Control", DEFAULT_CACHE_CONTROL_HEADER_VALUE) .body(json!(response_object).to_string()) // given some Error implements IntoResponse, so axum can convert it correctly .map_err(|_| SomeError::INTERNAL_PROCESSING_ERROR)?) or Ok(Response::builder() . status(StatusCode::OK) .header("Cache-Control", DEFAULT_CACHE_CONTROL_HEADER_VALUE) .body(json!(response_object).to_string()) // given your return type is Result<Response, (StatusCode, String)> .map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Processing failed".into())?) But I think to have understood that you do something like this?: get_optional_value() .ok_or_else(|_| Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty())...???) If that's the case, I think the same rules apply. If it is completely static, use expect. Your hard-coded response not building correctly is a bug: get_optional_value() .ok_or_else(|_| Response::builder().status(StatusCode::NOT_FOUND).body(Body::empty()).expect("Oops, bug!")) If it is highly dynamic, you have a problem because your return type basically needs a Response but building that response is fallible, which would lead to an infinite loop of map_err's with question marks (I hope you understand what I mean). So my suggestion: Either make your peace with expect, or change the return type of your handler function to something more flexible like: Result<Response, (StatusCode, String)> or Result<Response, impl IntoResponse>, which gives you a lot more flexibility to define your errors. Alternatively, create an error type that implements IntoResponse (which also carries the risk of having to build a fallible Response again that...yea...might end in the same infinite loop of error handling). Does this help, or shall we go over this in more detail? :)

  • @abdulrahmanmohamed8298
    @abdulrahmanmohamed8298 หลายเดือนก่อน

    Great video! Learned something new about unwrap() / expect() p.s is the theme you are using the Night Owl theme?

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Hey, glad to hear that! Yes, it is. ☺️

  • @DanielSantanaBjj
    @DanielSantanaBjj หลายเดือนก่อน

    Fantastic work

  • @edgeeffect
    @edgeeffect หลายเดือนก่อน

    I don't like the "zero" in "zero cost abstractions"... I'd be OK with "low cost" or even "very low cost" but any time you see anything claim to be "zero cost" you know you're looking at a lie.

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Agree. Some cost is always associated with something. But as said: zero-additional cost would also be okay, for me. ☺️

  • @peterryszkiewicz4354
    @peterryszkiewicz4354 หลายเดือนก่อน

    Nice video. One nice alternative to unwrap/expect is the let-else pattern. Example: let Some(value) = some_option else { return /* or break/continue/etc */}. Thereafter "value" holds the unwrapped value, and you've handled the error case.

  • @khai96x
    @khai96x หลายเดือนก่อน

    The code example has a lot of duplicated works. If you both `value.contains('=')` and `value.split('=')` with matching the result of `value.splitn(2, '=')`, all panics would be eliminated.

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      I am well aware of that, but that was not the main point of the video, which is why I used an example everyone would understand, no matter their experience in Rust. ;) And no, multiple equals signs never panic. They just return an err because for this particular example, we only allow key=value. If you really want equals signs to be allowed in either key or value, I’d actually involve quotes in the grammar, like most sane languages and parsers do.

  • @luigidabro
    @luigidabro หลายเดือนก่อน

    Me who uses unwrap_unchecked and pointer manipulation to flatten a vector of arrays

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      If you REALLY know what you're doing…you're free to. 😂

  • @LinkiPinkiWasTaken
    @LinkiPinkiWasTaken หลายเดือนก่อน

    What about cases where you want to convert something into a new owned object, from a borrowed value? Is `impl From<&MyStruct> for MyOtherStruct` bad practise or did you just not mention it? If it is, why is it bad?

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      You can well do that. A common impl I see (and also use) is From<&str>, for example, and even String implements From<&str>. :) The only thing From implies (by the docs is): The conversion MIGHT not be cheap, or you MUSTN'T rely on it being cheap. It does not specifically say anything about the base value, although in theory, From is meant to take ownership. But in the end, it's perfectly fine to do that. The docs just list a few requirements that are usually associated with the conversion: 1. The conversion is *infallible* 2. The conversion is *lossless* 3. The conversion is *value-preserving* 4. The conversion is *obvious*

  • @CodeVault
    @CodeVault หลายเดือนก่อน

    Great video! I even learned a few new things regarding implementing your own error type. Instead of expect I would use ".map_err(...)?", ".ok_or(...)?" or even just "?" in parts of code where I know they shouldn't panic regardless of what the programmer does (api calls for example). In parts of code where I definitely need to stop the whole process (say, a database connection error or missing .env variables) I just use ".expect(...)" as shown

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Yep! The "really" best way to express the problem in Rust is probably this implementation (as already shown and discussed in other comments): fn try_from(input: &str) -> Result<Self, Self::Error> { let mut split = input.split('=').map(str::trim).map(str::to_owned) match (split.next(), split.next(), split.next()) { (Some(key), Some(value), None) => Ok(Self{ key: key.to_owned(), value: value.to_owned() }), _ => Err(ParsingError::MalformedRecord(input.into())), } } I generally agree that I'd do it this way. In this case, I just had to make an easy-enough example to showcase the problem, which also does not turn away complete Rust newbies. So in general, in this example, you CAN "implement the problem away" by using more advanced language features. :)

    • @CodeVault
      @CodeVault หลายเดือนก่อน

      @@oliverjumpertzme That's a creative way of using pattern matching. Didn't even cross my mind. I guess the only downside is it's allocating a tuple. Might use that in my parsing implementations from now on actually Also, I agree, sometimes just using "match" is better. Especially if you need to treat errors as "warnings" and use a control statement such as "continue;"

  • @RomanAvdeevX
    @RomanAvdeevX หลายเดือนก่อน

    Will it fail if it has "key=" ?

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      No, it would result in a: Record { key: "key", value: "" } :)

  • @vasiliigulevich9202
    @vasiliigulevich9202 หลายเดือนก่อน

    The guy forgot to show how to refactor the code to make unwrap unnecesary

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      ”The guy” had a point to make which was not to optimize each and every bit of some code. 😉

  • @FrancescoBochicchio-ly6du
    @FrancescoBochicchio-ly6du หลายเดือนก่อน

    AFAIK, panic only terminate the current thread, other threads keep running if the crashed one is not the main one.

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Yes. As shown. But for many programs, even a secondary thread panicking can bring the whole system down. ☺️

  • @sunilpaul6891
    @sunilpaul6891 หลายเดือนก่อน

    Would it not be better in the parser example to make the error condition `!=`?

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Do you mean: if split.len() != 2 { return Err(ParsingError::MalformedRecord(value.into())); } Yea, that also works. :) There are several ways to do it. I chose this approach to illustrate the overall thing better. Optimization is a good thing, but it often costs additional explanation. View this just as example code to prove a point.

  • @lcssbr
    @lcssbr หลายเดือนก่อน

    Great video and I learning a few things and helped me remember other things I was almost forgetting about. Thanks!

  • @OfficialViper
    @OfficialViper หลายเดือนก่อน

    You're the best Rust TH-camrs. Thanks! :)

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Awwww, I am sure I still have a lot to learn, but this makes my day…so thank you! 💛

  • @miriamramstudio3982
    @miriamramstudio3982 หลายเดือนก่อน

    Great video. Thanks

    • @oliverjumpertzme
      @oliverjumpertzme หลายเดือนก่อน

      Thanks for watching and the feedback 💛🙏🏻