5 traits your Rust types must implement

แชร์
ฝัง
  • เผยแพร่เมื่อ 24 ธ.ค. 2024

ความคิดเห็น • 115

  • @letsgetrusty
    @letsgetrusty  ปีที่แล้ว +5

    📝Get your *FREE Rust cheat sheet* :
    www.letsgetrusty.com/cheatsheet

    • @jacquesfaba55
      @jacquesfaba55 ปีที่แล้ว +8

      No

    • @olivarra1
      @olivarra1 ปีที่แล้ว +4

      I'm genuinely curious - Why do you keep promoting the free cheat sheet on every. single. one. of. your. videos?
      Don't get me wrong, you make good content and your cheatsheet is really good, so I do appreciate that, but it's always those 5 seconds in your videos that I have to mentally ignore because I already know about it.

    • @g227x01
      @g227x01 ปีที่แล้ว +4

      @@olivarra1 To get to the cheat sheet, you need to give an email and name. He's getting a lead in return (that may be used for inbound marketing). You "pay" with your lead info.

    • @bread8176
      @bread8176 ปีที่แล้ว +3

      I'm not giving you my email address

  • @mrme5694
    @mrme5694 ปีที่แล้ว +49

    I loved the fact that he makes things that look intimidating to a new learner much easier by diving straight right into it. He doesnt beat around the bush, too, no unnecessary bs. Only what is needed.

  • @oriontvv
    @oriontvv ปีที่แล้ว +57

    8:20 Just wanted to notice that serde can skip field db because Db implements Default trait, otherwise would be compile error

    • @damonpalovaara4211
      @damonpalovaara4211 ปีที่แล้ว +5

      You can also configure serde to call a function that returns that type

    • @cozyGalvinism
      @cozyGalvinism ปีที่แล้ว +2

      Don't skip deserialization on a default value by default. It's bad practice, rather point the default parameter of the serde attribute to the default function. That way you can still deserialize a value if it's present but default when it's not.

  • @TheTmLev
    @TheTmLev ปีที่แล้ว +15

    Your library shouldn't implement Send + Sync if it doesn't make sense. Users can wrap T in Arc if they really need it.

    • @Андрей-ю2р6л
      @Андрей-ю2р6л ปีที่แล้ว +12

      Also it's not always good to implement default trait, because sometimes a type is expected to always hold a non-trivial value. Users can use Option if they really need default value

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

      @@Андрей-ю2р6л ​ @user-ne1nw6hw2q So for example, a http status code shouldn't implement default trait because 0 is not valid http status, am I correct?

  • @orterves
    @orterves ปีที่แล้ว +11

    The feature flag approach is beautiful - a real have your cake and eat it too moment

  • @waynr
    @waynr ปีที่แล้ว +12

    Probably the only trait here that should always be implemented is Debug. Library authors can have good reasons for not implementing the others.

    • @Derik.
      @Derik. ปีที่แล้ว +1

      The title is meant to catch your attention. It's hyperbole. Yes, library authors shouldn't implement the traits if they have good reason not to. Otherwise they should keep them in mind.

  • @IvanDeMarino
    @IvanDeMarino ปีที่แล้ว +4

    Thank you so much for this video: you made me add a bunch of feature flags and a new release for one of my crates, purely inspired by this content.

  • @londospark7813
    @londospark7813 ปีที่แล้ว +10

    Thank you, great video and I'm really glad you showed how to feature-gate serde.

  • @v0xl
    @v0xl ปีที่แล้ว +12

    You should also derive Copy as well as Clone if the type you're exposing is supposed to be copied (like no heap allocated things like vecs or strings will be added to it in the future), and also should always add it to all basic enums that don't store any data.
    serde serialize and deserialize should probably be behind an optional feature, because not all people need serde

    • @Rangsk
      @Rangsk ปีที่แล้ว +13

      > serde serialize and deserialize should probably be behind an optional feature, because not all people need serde
      8:34

  • @n0kodoko143
    @n0kodoko143 ปีที่แล้ว +2

    Noob here. Super cool use of cfg attributes and features! This languages get cooler everyday (that I learn more about it)

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

    Hey, this is nth video from you that I am watching and I just want to say thanks for all this content. I have been on my Rust learning journey for a while and only recently am I feeling productive enough in my project. There are still tons of things to learn but Rust makes getting started much easier than I would have expected from a systems language.

    • @letsgetrusty
      @letsgetrusty  7 หลายเดือนก่อน +1

      Glad I could help!

  • @viniciusataidedealbuquerqu2837
    @viniciusataidedealbuquerqu2837 ปีที่แล้ว

    amazing in a nutshell. this is incredible how I have less fear programming in rust traits now

  • @normiemango
    @normiemango ปีที่แล้ว +3

    Rustacean army come in! 🦀🦀🦀

  • @MasterHigure
    @MasterHigure ปีที่แล้ว +7

    Just so you know: The J and Gj in Jon Gjengset are soft. It's pronounced more like "Yon Yengset". Not that I blame you, I don't expect people to know how to pronounce names from a language they don't know.

    • @linkernick5379
      @linkernick5379 ปีที่แล้ว

      Good to know, I didn't know that too.

    • @31redorange08
      @31redorange08 ปีที่แล้ว

      Well, he has access to the internet to look it up.

    • @MasterHigure
      @MasterHigure ปีที่แล้ว +1

      @@31redorange08 Names in particular aren't that easy to look up. Regular words you can find in dictionaries, and some dictionaries have pronunciation guides. But proper nouns is not so easy.

  • @Amplifity
    @Amplifity ปีที่แล้ว +10

    Great video. Thanks for your efforts. I learn a lot from you.

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

    So basically I can have one struct and trait along with it implementation block. Now I can use this trait implementation on the other struct and override the base trait if I want by creating impl block and change the functionality in it. I'm new to rust and exploring how to have inheritance like functionality in rust via composition. I require some good references as I can't find many good example anywhere

  • @daveduvergier3412
    @daveduvergier3412 ปีที่แล้ว +1

    Very nice explanation of feature switches there

  • @MH_VOID
    @MH_VOID ปีที่แล้ว +8

    8:10 why not use a raw string literal (r#"..."#) for `user_str`?

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

    Using Serde to apply strict typing to JSON input strings so easily is BY FAR the greatest value I've received from this video. Way to bury the lead! 😅

  • @jefffriedman6942
    @jefffriedman6942 ปีที่แล้ว +6

    Isn't it inefficient to use Arc where Rc would work? That should be mentioned, since this is not a free modification.

    • @goviczek
      @goviczek ปีที่แล้ว

      I thought the same. I'm wonder if it could be implemented as feature. If feature e.g. thread_safe is active use Arc otherwise Rc. I think, its quite a common problem. Is a standard solution for that in Rust?

    • @goviczek
      @goviczek ปีที่แล้ว

      O maybe just use generic type parameter for pointer type. With default Rc.

  • @after_alec
    @after_alec ปีที่แล้ว +1

    Also, Copy instead of Clone if your type can implement it!

  • @F776-b2s
    @F776-b2s 8 หลายเดือนก่อน +1

    Wow, I was implementing PartialEq manually with match cases

  • @kiransingh2935
    @kiransingh2935 ปีที่แล้ว +1

    I only just realized that serde is a portmaneau of serialize-deserialize.

  • @QuayTech
    @QuayTech ปีที่แล้ว

    8:27 Why does It show 2 users printing in the log?

  • @le_moski
    @le_moski ปีที่แล้ว +2

    What extension/settings do you use to get errors typed like that while coding?

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

    nice vid, one question, whats that extension called when the red text is being shown?

  • @chrishabgood8900
    @chrishabgood8900 ปีที่แล้ว +1

    do you have to derive each time?

  • @what42pizza
    @what42pizza ปีที่แล้ว +3

    I feel like it's better to have separate types for atomics since they're a bit slower.
    Example:
    pub struct User {
    ...
    db: Rc,
    }
    pub struct AtomicUser {
    ...
    db: Arc,
    }

    • @LimitedWard
      @LimitedWard ปีที่แล้ว +1

      Wouldn't you be losing even more speed when having to switch between types?

    • @what42pizza
      @what42pizza ปีที่แล้ว

      @@LimitedWard What do you mean by switching between types?

    • @donizetevida2149
      @donizetevida2149 ปีที่แล้ว

      ​@@LimitedWardyou will use first or second struct. The way it was shown on video, you will be obligated to use Arc type, which is slow. If user don't need arc, it must simple use "User" type, as commented above, else it must use second type.

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

      You could use a generic

  • @shahriarzaman4715
    @shahriarzaman4715 ปีที่แล้ว

    So, If you don't own Role struct, how can you implement debug/clone/xyz trait?

  • @ZekeFast
    @ZekeFast ปีที่แล้ว

    Bogdan, at 6:55 you some how abruptly cut you video and jumped to serde topic without showing that Arc fixed the issue or showing any consequences of changes from Rc to Arc which feels a bit weird and unfinished. Also you haven't present any solution from the John's book. JFYI. Also you touched very nice topic about non-sendable types. So, I have a question. What if you have a type which need to be Send-able, like your User to be used in e.g. Axum, but you don't own it and it contains Rc which makes it non-sendable. What would be a solution to make such type sendable?

  • @ishanksharma9051
    @ishanksharma9051 ปีที่แล้ว

    amazing video, keep it up. I was about to comment on the feature flag for serde!!

  • @CorentinWay
    @CorentinWay ปีที่แล้ว +1

    Always great vidéos as always... I see many usefull addine plugins on vs code or the terminal (autocomplete) can you give us some of them ? Or do a video about them.

  • @hilal53426
    @hilal53426 ปีที่แล้ว +2

    You are really doing great work! do you have a Udemy course?

  • @gabrielcox10
    @gabrielcox10 ปีที่แล้ว

    I NEED HELP! how do i use a code written in rust?

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

      YT is not a good forum to get help with code.

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

    Can’t rust provide these traits by default?

  • @a_maxed_out_handle_of_30_chars
    @a_maxed_out_handle_of_30_chars ปีที่แล้ว +1

    this was awesome, thank you :)

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

    You are The MAN!

  • @hotfishdev
    @hotfishdev ปีที่แล้ว +3

    I’m not too wild about your use of the term “should” in this video. Fine otherwise, but Rust has so many targets and use cases where you definitely shouldn’t use ARC instead of Rc or waste time including Serde support (embedded comes to mind), that laying down these things as absolutes to newbs without caveat is, imo, kinda harmful.

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

    Super useful and helpful, thanks!

  • @sinaebr7337
    @sinaebr7337 ปีที่แล้ว

    love this type of videos. thanks

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

    Please don't blindly derive Default unless the resulting value actually makes sense in the context of your type (e.g. if you have an identifier type Default with an empty string makes no sense).

  • @InMemoryOfNeo
    @InMemoryOfNeo ปีที่แล้ว

    1:12 how are you making these codes coming to screen like that?

  • @chrisalexthomas
    @chrisalexthomas ปีที่แล้ว +96

    I'm still laughing at STD traits....I know what it means... but it's so funny anyway...

    • @lua-nya
      @lua-nya ปีที่แล้ว +12

      Somehow I understand what you mean but not why you find it funny.

    • @tbird-z1r
      @tbird-z1r ปีที่แล้ว +29

      @@lua-nya STD used to stand for subscriber trunk dialling, which is how phone lines used to handle out of area calls.
      He's clearly laughing at the juxtaposition of the "old school" phone lines with the "new kid on the block" Rust.

    • @normiemango
      @normiemango ปีที่แล้ว +1

      ​@@lua-nya I agree.

    • @lua-nya
      @lua-nya ปีที่แล้ว

      @@tbird-z1r Well thank you for the explanation, now I understand.

    • @electrolyteorb
      @electrolyteorb ปีที่แล้ว

      Sexually transmitted diseases

  • @krisaor
    @krisaor ปีที่แล้ว

    Thanks! great explanations!

  • @henrymaddocks984
    @henrymaddocks984 ปีที่แล้ว

    Excellent video 👍🏼

  • @JS-fd5oh
    @JS-fd5oh ปีที่แล้ว +5

    As a user of the lib, I'm concerned about code bloat that comes with libs. The author of the lib ASSUMED I will need it. What if I don't use any of these Debug, Sync etc in my code but they still get imported with the lib? Will rust compiler cut them out from my binary if my code doesn't use any of these derived traits?

    • @AshtonSnapp
      @AshtonSnapp ปีที่แล้ว +12

      Send & Sync are just marker traits as far as I am aware (no actual functionality, just flags that tell the compiler that certain multithreading things are safe). As for the others, the compiler is based on LLVM and _should_ automatically remove unused code from the compiled output (at least in release builds). So you should be good.

    • @JS-fd5oh
      @JS-fd5oh ปีที่แล้ว

      @@AshtonSnapp I'm not sure they are just marker traits. I think the macro literally embedds trait implementations into your code like any other macro does. So you end up with the implementation for Sync, Debug etc.

    • @CalebTerryRED
      @CalebTerryRED ปีที่แล้ว +6

      Sync is different from debug though, it doesn't have any associated methods to be added to a binary. The only place the trait could be used is by the compiler when type checking functions, it won't exist at any lower levels. Traits with associated functions or values like debug are a little bit different, but still should have their functions removed if they're unused

    • @JS-fd5oh
      @JS-fd5oh ปีที่แล้ว +1

      @@CalebTerryRED Thanks for explanation. One concern. Should? Or Will be removed? :)

    • @stalker32041
      @stalker32041 ปีที่แล้ว +1

      ​@@JS-fd5oh should and will be removed.

  • @criptouni
    @criptouni ปีที่แล้ว +1

    I actually tend to look for ::new instead of Default ... but I guess ::new without any args is Default LOL
    any tips on that @letsgetrusty ?

  • @mcpecommander5327
    @mcpecommander5327 ปีที่แล้ว

    Society when rust adds Debug to the list of default traits

  • @GlobalYoung7
    @GlobalYoung7 ปีที่แล้ว

    thank you 👍

  • @linkernick5379
    @linkernick5379 ปีที่แล้ว +1

    Unfortunately, there is no easy way to have Debug trait implemented for a struct or enum, containing function type. JS, as opposite, does have it by default.

  • @diadetediotedio6918
    @diadetediotedio6918 ปีที่แล้ว

    Is this really? I do remember I implemented a trait for a foreign type these days, for testing a concept that I had in mind about extension functions

    • @workflowinmind
      @workflowinmind ปีที่แล้ว

      You must have wrapped it as it's not possible

    • @diadetediotedio6918
      @diadetediotedio6918 ปีที่แล้ว

      @@workflowinmind
      No, I really did not wrapped it, really.

    • @diadetediotedio6918
      @diadetediotedio6918 ปีที่แล้ว

      @@workflowinmind
      You can try it for yourself:
      ```rust
      trait StringExt {
      fn print_it(&self);
      }
      impl StringExt for String {
      fn print_it(&self) {
      println!("It is: {}", self);
      }
      }
      fn main() {
      let msg = "Hello, World!".to_string();
      msg.print_it();
      }
      ```

    • @LawlessSentry
      @LawlessSentry ปีที่แล้ว +2

      @@diadetediotedio6918 I think he said foreign traits AND foreign types, if you have either of them locally defined you can implement it.

    • @diadetediotedio6918
      @diadetediotedio6918 ปีที่แล้ว

      @@LawlessSentry
      OOO, that makes sense, thanks! But why is this the case?

  • @adibhanna
    @adibhanna ปีที่แล้ว

    I was working on a similar video :D

  • @modernkennnern
    @modernkennnern ปีที่แล้ว

    Now people are telling me to exposing my STDs.. smh
    Good video 👍

  • @MrEW1985
    @MrEW1985 ปีที่แล้ว +1

    It was a nice and easy video until you started with serialization code.

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

    Drop the music.

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

    Adding unnecessary traits can really slow down compile times.

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

      Yeah first compile time is slow

  • @not_herobrine3752
    @not_herobrine3752 ปีที่แล้ว

    unbelievable

  • @SchmySeymour
    @SchmySeymour ปีที่แล้ว

    I know it's a convention in tech instructions to use the type of something as the name, but it's a terrible convention that makes reading and interpreting difficult for beginners.
    I stopped watching the video around 1:20 when I saw the implementation of the User type was named 'user'. Put another way, the line
    let user: User = User {
    may as well say, "bar bar bar bar bar bar bar bar bar bar bar" for all of the nuance it provides. This isn't BrainF**k, after all.
    Please, for the love of clarity, stop using the same name for types and their implementations.
    Give us tangible, meaningful examples. Like the type is "Vehicle" and the implementation is "car", or type is "Animal" and implementation is "dog", or whatever, just not "Thing" and "thing".
    It's bad enough that the documentation gives "path" as both a crate and a string name in the one example:
    use std::path::Path;
    ...
    let path = Path::new("./foo/bar.txt");