Це відео не доступне.
Перепрошуємо.
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
📝Get your *FREE Rust cheat sheet* :
www.letsgetrusty.com/cheatsheet
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`.
C also doesn’t have a new keyword.
@@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.
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
Nice! Love the idea of a "idiomatic Rust" video series. Keep them coming!
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.
+1 for default arguments.
What’s the issue with builder pattern though?
@@sohn7767 it gets unreadable real quick
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.
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()
});
}
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.
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.
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.
I love how clear your videos are, thank you so much 🙇
unwrap_or_default was worth the price of admission
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. :)
This video is great! Yes yes, more idiomatic Rust. Love it !
Super useful video, thank you! Can someone explain me, why we had to use "to_owned()" everywhere? Could I also use "String::from()" instead?
it's preference. I also like String::from more
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?
@@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
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.
@@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
Thanks, man! Great videos. Every day, my love for Rust grows. I finally found my favorite programming language.
Great video. Congrats and keep going with this great job!
It's crazy. I just checked to see if there are any new uploads. And this shows up.
Great video by the way.
Excelent video ! This is what I expect from this channel !!! Very usefull, please make more videos like this.
fuck yeah i wanna see more videos on idiomatic rust.... you the bomb bogden...
thanks for your videos. best way to learn and idiomatic way!
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.
Cool......., please more about Idiomatic rust..
I liked the series so much. I watched it again.
Thanks for your job. Great! I am awaiting for your idiomatic Rust lessons.
Wonderful! Please have more Idiomatic Rust .
More idiomatic vids please, thanks 🙏
Was useful learning about the Default trait.
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
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.
Nice video !
Heyy Bogdan
Could you make a Video on the From and Into traits? I find them confusing.
what font do you use in vs code
Thanks. Great video.
great video profesor!
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"...)
of course, we want more videos.
Great stuff!
What extension are you using for VSCode?
He has a video about it.
What does the :? Mean in the print macro?
Use the output implemented by the Debug trait rather than the output implemented by the Display trait (when using {})
@@jasperdevries1726 ok thanks
There's also :#? to get a "pretty" form of the Debug output.
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 😉
Nice job!
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?
nvm missed the check part in the new fn
thank you 😊
Yo some embedded rust series?
No.
How's this idiomatic if it's not even supported? Referring to the named function arguments on the caller side.
cheeeee sheeeee ❤
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
Moar
why could not you just show a simple constructor for a simple object like a Point or something?
why need to complicate stuff?
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.
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.
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)
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.
It also happens if other languages with static methods