Це відео не доступне.
Перепрошуємо.

Idiomatic Rust - Constructors

Поділитися
Вставка
  • Опубліковано 18 сер 2024
  • The Rust programming language has a lot of great features but it's not always obvious how to write Rust code in an idiomatic way. So today we are starting a series all about idiomatic Rust! In this video I cover constructors in Rust.
    📝Get your FREE Rust cheat sheet :
    www.letsgetrus...
    Code: github.com/let...
    Chapters:
    0:00 Intro
    0:25 Rust has only one true constructor
    2:40 The new constructor function
    5:47 Default constructors
    8:31 Deriving the Default trait
    10:00 The derive-new crate
    12:39 Outro
    #rust #programming #idiomatic

КОМЕНТАРІ • 73

  • @letsgetrusty
    @letsgetrusty  2 роки тому +2

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

  • @scheimong
    @scheimong 2 роки тому +91

    I think it's important to emphasise that unlike many other languages in the "C family", `new` IS NOT a keyword in Rust. The constructor function is just a regular associated function that is conventionally named `new`.

    • @yoshiyahoo1552
      @yoshiyahoo1552 Рік тому +14

      C also doesn’t have a new keyword.

    • @franciscoflamenco
      @franciscoflamenco Рік тому +2

      @@yoshiyahoo1552 Exactly what I was thinking. To me it's an OOP keyword, and languages inspired by Java or C++ (which itself inspired Java) have it because they're OOP and not because they're C-like. I could be mistaken but I believe the keyword comes from Smalltalk, where in an interesting parallel to Rust it also happens to be just a regular message and not a keyword.

  • @Willyuum
    @Willyuum 2 роки тому +23

    I'm new to rust and have been self learning through reading the rust book, but these rust tutorials are soo helpful and make me learn the power of the language faster, I'm so happy to find this youtube channel.
    I think it's gonna help a lot of developers who wants to join Rust

  • @DrIngo1980
    @DrIngo1980 2 роки тому +15

    Nice! Love the idea of a "idiomatic Rust" video series. Keep them coming!

  • @linkernick5379
    @linkernick5379 2 роки тому +25

    I'm personally hoping we will get named/default arguments sooner than later, before things like the builder pattern get too ingrained. Builder pattern is too clunky and I'm trying to avoid them as much as possible despite the existence of crates, implementing the annotations for builder's scaffolding.

    • @sohn7767
      @sohn7767 2 роки тому +7

      +1 for default arguments.
      What’s the issue with builder pattern though?

    • @proloycodes
      @proloycodes 2 роки тому +1

      @@sohn7767 it gets unreadable real quick

    • @MasterHigure
      @MasterHigure 2 роки тому +6

      A well-implemented struct where default arguments make sense have separate constructors depending on which arguments you want to supply. There is likely a reason the Rust team has specifically avoided default arguments, and I don't think it's implementation difficulty.

    • @raffimolero64
      @raffimolero64 2 роки тому

      pub struct FuncOptions {
      pub opt1: i32,
      pub opt2: i32,
      pub opt3: i32,
      }
      impl Default for FuncOptions { /* */ }
      fn some_func(required_arg: i32, options: FuncOptions) { /* */ }
      fn caller() {
      some_func(5, FuncOptions {
      opt3: 24,
      ..Default::default() // alternatively, ..FuncOptions::default()
      });
      }

  • @isaiah12-2
    @isaiah12-2 11 місяців тому +2

    Yes, I would love to see more of these. This is incredibly high quality content. I would like to thank you, Bogdan, for single-handedly teaching me a large percentage of all rust I know, and keeping me going with it. Thanks and God bless.

  • @leprofesseurshen
    @leprofesseurshen 2 роки тому +2

    My company is currently switching from Go to Rust and I need to learn Rust so I can start to port old projects. I find your videos so helpful in my learning process. Thanks so much.

  • @hobbes5043
    @hobbes5043 2 роки тому +3

    This is one of the clearest programming channels I have encountered in a while. Coming from the world of JavaScript, I REALLY, REALLY appreciate the precision with which everyone speaks about Rust (i.e. it's "idiomatic" to speak about Rust intelligently). This is coming from the intellectual cesspool that is web programming these days, where it's a race to the bottom to see how unintelligently articles are written about the language, to the point where it's almost childish and certainly inaccurate. w3schools, DeepSeaOcean (or whatever it's called), and plenty other big names talk about web programming as if they are trying to convince people that hate math and science that they should be programmers.
    In any case, most Rust practitioners I've come across try to describe the syntax and behavior of the language as correctly as possible, using the correct terminology as much as possible. This kind of environment is the thing I miss the most about grad school. Thank you for creating these videos, you exemplify everything I just said about Rust.

  • @Defrost2157
    @Defrost2157 2 місяці тому

    I love how clear your videos are, thank you so much 🙇

  • @henrymaddocks984
    @henrymaddocks984 2 роки тому +2

    unwrap_or_default was worth the price of admission

  • @Yukicanis
    @Yukicanis Рік тому +1

    I wish the new function wouldn't be just a convention but a fixed name like Pythons __init__. This would make foreign code more readable. :)

  • @HermanWillems
    @HermanWillems 2 роки тому +3

    This video is great! Yes yes, more idiomatic Rust. Love it !

  • @Ma1ne2
    @Ma1ne2 2 роки тому +19

    Super useful video, thank you! Can someone explain me, why we had to use "to_owned()" everywhere? Could I also use "String::from()" instead?

    • @inx1819
      @inx1819 2 роки тому +10

      it's preference. I also like String::from more

    • @BenjaminWheeler0510
      @BenjaminWheeler0510 2 роки тому

      Could you remind me the purpose of these two function calls? I think string from is because the literal is a str rather than a String, but does to_owned do the same thing?

    • @bababert8488
      @bababert8488 2 роки тому

      @@BenjaminWheeler0510 Strings cointain String slices and since he used a static String slice I guess he just wrapped a String around. Thats just my explenstion though and I dont know if its more efficient

    • @markmcdonnell
      @markmcdonnell 2 роки тому +6

      Many years ago to_owned was considered better because it would make less allocations. But if you check the rust source code you'll find the performance is the same now as to_string just calls to_owned under-the-hood.

    •  2 роки тому +2

      @@markmcdonnell I read old article about performance(+- 10%) , but I check now the code and its true, to_string call string::from that call to_owned and all are inline,
      ty for this information

  • @yos2413
    @yos2413 9 місяців тому

    Thanks, man! Great videos. Every day, my love for Rust grows. I finally found my favorite programming language.

  • @marcosadriano05
    @marcosadriano05 2 роки тому +3

    Great video. Congrats and keep going with this great job!

  • @ramesses_ii
    @ramesses_ii 2 роки тому

    It's crazy. I just checked to see if there are any new uploads. And this shows up.
    Great video by the way.

  • @sergiuoanes4635
    @sergiuoanes4635 2 роки тому

    Excelent video ! This is what I expect from this channel !!! Very usefull, please make more videos like this.

  • @jasonlantz3808
    @jasonlantz3808 2 роки тому +1

    fuck yeah i wanna see more videos on idiomatic rust.... you the bomb bogden...

  •  2 роки тому +1

    thanks for your videos. best way to learn and idiomatic way!

  • @AlexanderArtamonov
    @AlexanderArtamonov 5 місяців тому

    Apart from the fact that "Factory method" entitled as "object oriented pattern" the design solution itself - not to call constructor directly and get significant flexibility with function, is very common across many different languages.

  • @saaddahmani1870
    @saaddahmani1870 2 роки тому +1

    Cool......., please more about Idiomatic rust..

  • @jonathanmoore5619
    @jonathanmoore5619 2 роки тому

    I liked the series so much. I watched it again.

  • @carmelostagno6352
    @carmelostagno6352 Рік тому

    Thanks for your job. Great! I am awaiting for your idiomatic Rust lessons.

  • @goodwish1543
    @goodwish1543 2 роки тому

    Wonderful! Please have more Idiomatic Rust .

  • @epiderpski
    @epiderpski 2 роки тому +2

    More idiomatic vids please, thanks 🙏

  • @markmcdonnell
    @markmcdonnell 2 роки тому

    Was useful learning about the Default trait.

  • @ringo.gg.
    @ringo.gg. 2 роки тому +2

    Nice video and series as always! Regarding the random id generation, is there an idiomatic way in rust to have shared variables across all struct instances? Similar to static attributes in OOP languages that are attached to the class itself and not an specific instance

    • @McMrMinecraft
      @McMrMinecraft 2 роки тому +2

      You can declare a `static mut` scoped under a struct's impl block (it would be accessed by doing `TypeName::STATIC_MUT`), although mutating static variables has to wrapped in an `unsafe` block because mutable statics are not guaranteed to be thread-safe.

  • @Polynuttery
    @Polynuttery 6 місяців тому +1

    Nice video !

  • @johanneslade2830
    @johanneslade2830 2 роки тому +1

    Heyy Bogdan
    Could you make a Video on the From and Into traits? I find them confusing.

  • @fus3n
    @fus3n 2 роки тому +1

    what font do you use in vs code

  • @tak68tak
    @tak68tak 2 роки тому

    Thanks. Great video.

  • @juancastillo2548
    @juancastillo2548 2 роки тому

    great video profesor!

  • @modernkennnern
    @modernkennnern 2 роки тому +2

    I think it's very unfortunate that you're practically forced to go away from the clean object initialization route to using a constructor function which makes it a lot harder to understand what each parameter does. "Is the first parameter the first name or the last name? >"first_name: "bob"< is a lot clearer than >::new("bob"...)

  • @dimitrobest5293
    @dimitrobest5293 2 роки тому

    of course, we want more videos.

  • @_jdfx
    @_jdfx 2 роки тому

    Great stuff!

  • @Otakutaru
    @Otakutaru 2 роки тому +1

    What extension are you using for VSCode?

    • @RoDmtr
      @RoDmtr 2 роки тому

      He has a video about it.

  • @redcrafterlppa303
    @redcrafterlppa303 2 роки тому +1

    What does the :? Mean in the print macro?

    • @jasperdevries1726
      @jasperdevries1726 2 роки тому +5

      Use the output implemented by the Debug trait rather than the output implemented by the Display trait (when using {})

    • @redcrafterlppa303
      @redcrafterlppa303 2 роки тому

      @@jasperdevries1726 ok thanks

    • @peter9477
      @peter9477 2 роки тому +3

      There's also :#? to get a "pretty" form of the Debug output.

  • @DrumMeister
    @DrumMeister 2 роки тому

    Very nice video 👌
    I have a good tip in duplicating lines in VSCode, just do ctrl+c, ctrl+v on the line you want to duplicate 😉

  • @ClearerThanMud
    @ClearerThanMud 2 роки тому

    Nice job!

  • @TillmannHuebner
    @TillmannHuebner 2 роки тому

    What am i missing here? Why does changing the passed in username from testuser123 to testuser1234 one the one hand return the default and on the other hand an initialized version?

  • @GlobalYoung7
    @GlobalYoung7 2 роки тому

    thank you 😊

  • @dibyojyotibhattacherjee4279
    @dibyojyotibhattacherjee4279 2 роки тому +1

    Yo some embedded rust series?

  •  Рік тому

    How's this idiomatic if it's not even supported? Referring to the named function arguments on the caller side.

  • @dodalovic
    @dodalovic Рік тому

    cheeeee sheeeee ❤

  • @tommy.3377
    @tommy.3377 3 місяці тому

    Best video but the most annoying thing to hear was the keyboard... I really didn't find it any charming ... I hope you will fix it next time ... In the newest videos

  • @jobosan4855
    @jobosan4855 2 роки тому

    Moar

  • @footballCartoon91
    @footballCartoon91 Рік тому

    why could not you just show a simple constructor for a simple object like a Point or something?
    why need to complicate stuff?

  • @user-gk9eo5bq4z
    @user-gk9eo5bq4z 2 роки тому

    BTW, is it "idiomatic" to use method "new" with arguments? I guess its not! "new" shouldn't be used in cases, where arguments are needed to construct new instance. In fact, rust's std library itself follow this pattern.

    • @peter9477
      @peter9477 2 роки тому +4

      I'm not sure it's true that new() should not have arguments. There's already default() for that, and it's pointless to have them do the same thing. Also I've seen quite a few libraries where new() takes arguments.

  • @hineko_
    @hineko_ 2 роки тому

    it always appeared so illogical to me that we have to call a method of the object that doesn't exist yet to create this object inside that method and then return it as the result... Oop was a mistake)

    • @chilly111
      @chilly111 2 роки тому +6

      You're calling a method of the class itself, not an instance. The class constructor often returns an instance of it's own type. Sorry this isn't in Rust terms but it's the same idea.

    • @someon3
      @someon3 Рік тому +1

      It also happens if other languages with static methods