Тёмный

Rust Programming - No Inheritance 

Jeremy Chone
Подписаться 24 тыс.
Просмотров 396 тыс.
50% 1

See the full video at ➜➜ • How does Rust make me ...
Help support this channel: / jeremychone
Rust Programming has no inheritance, but it is for the better. Checkout the full Top 5 Reasons How Rust Programming make us write good code: • How does Rust make me ...
Jeremy Chone:
- Twitter - / jeremychone
- Discord On Rust - / discord
- AWESOME-APP - awesomeapp.dev - Rust Templates for building awesome applications.
- Patreon - / jeremychone - Any help is a big help (for Rust educational content)
Other popular Rust Programming videos:
- AWESOME-APP Full Overview - Rust template for building Awesome Desktop Application: • Building Awesome Deskt...
- Tauri Quick Introduction (Desktop App wit Rust Programming): • Rust Tauri 1.0 - Quick...
- Rust Web App tutorials series: • Rust Web App - 1/3 - D...
- Rust Bevy Full Tutorial - Game Development with Rust: • Rust Bevy Full Tutoria...
- Rust for Java Developers series: • Rust for Java Develope...
Playlists:
- Rust For Desktop App: • Rust Programming for D...
- Everything Rust Programming - Tutorials, Courses, Tips, Examples: • Everything Rust Progra...
- Rust Programming for Web Development: • Rust Programming for W...
- Rust Courses: • Rust Course 2021 by th...
- Furst for Java Developers: • Rust for Java Developers

Наука

Опубликовано:

 

1 ноя 2022

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 409   
@okie9025
@okie9025 8 месяцев назад
OOP: everything is a class Rust: everything is an algebraic data type
@ksviety
@ksviety 8 месяцев назад
everything is an *object
@UNNIETKTJ
@UNNIETKTJ 7 месяцев назад
Oop is better 😢
@alice_in_wonderland42
@alice_in_wonderland42 7 месяцев назад
@@UNNIETKTJOop sucks aas
@skyy_xx
@skyy_xx 7 месяцев назад
@@UNNIETKTJ oop is dogshit
@ChannelCheesecake
@ChannelCheesecake 6 месяцев назад
@@UNNIETKTJScala can do both
@orange1304
@orange1304 Год назад
Cold shower everyone needs: There's nothing new after the Lisp.
@Rice7th
@Rice7th Год назад
I guess someone needs to do something about it
@unduloid
@unduloid Год назад
Well, counting parentheses ain't no fun, y'all!
@forgetfulfunctor1
@forgetfulfunctor1 Год назад
yeah I've been able to program emacs and gimp so hard with Lisp, so that makes it a general purpose language
@unduloid
@unduloid Год назад
@@forgetfulfunctor1 You're a hero, and your contributions to the world will not be forgotten!
@isodoubIet
@isodoubIet Год назад
IOW: Actually doing anything with lisp is so cumbersome that lispers are constantly impressed and shocked that Turing-completeness is a thing.
@motbus3
@motbus3 Год назад
One common misconception is that OO needs to be embedded in the language. You can model your entities with classes and implement without it. We just got used to have the full set
@Henry-sv3wv
@Henry-sv3wv Месяц назад
you can also invent GObject in c and then get disgusted and throw up that nobody not even the compiler helps you if you did something wrong. guess the vala language is the sulution for gui programming in gtk if you want a compiled language.
@HansBezemer
@HansBezemer 24 дня назад
I added OOP to my Forth compiler by simply creating a set of preprocessor macros (2K source). I did *all* design patterns (and more) to prove it is the real thing. Actually, C++ started its life as a C preprocessor - and there are still plenty of examples on the web how to add OOP to C. Basically, a class is nothing but a struct with function pointers - which are initialized at instantiation.
@HansBezemer
@HansBezemer 24 дня назад
@@Henry-sv3wv In Forth, you have to balance a stack. Every conditional or loop opens up a unique possibility to create a bug. It breeds discipline.
@motbus3
@motbus3 24 дня назад
@@HansBezemer in fact current Cpp implementation is not much different than that
@headlibrarian1996
@headlibrarian1996 21 день назад
@@motbus3 What the heck are you talking about? C++ compilers haven’t been C frontends for 25 years.
@randombleachfan
@randombleachfan Год назад
My life long dream of typing Floor(Floor) is finally possible 😎, Poggers
@alaouiamine3835
@alaouiamine3835 Год назад
Yo bleach is back bro, i can die now
@Rudxain
@Rudxain Год назад
Ah yes, the floor is made out of floor
@nicholasfinch4087
@nicholasfinch4087 Год назад
​@@Rudxainabsolutely beautiful 😂
@jo_kil9753
@jo_kil9753 Год назад
you'd need a box tho
@rurunosep
@rurunosep Год назад
@@jo_kil9753It's not a Floor struct containing a Floor struct. It's a Floor variant (for some enum) containing a Floor struct. They're separate things, so it's not a recursive definition.
@G11713
@G11713 Год назад
You can also implement common behavior on the `enum` type itself using a `match` statement to provide specific responses.
@wedata_unige
@wedata_unige Год назад
That's what I like. Rust implement algebraic data types instead of class for his construction
@boopumer
@boopumer 7 месяцев назад
Is it possible to define a trait which is implemented differently for each enum variant but call the different implementations on the enum variant?
@jcm2606
@jcm2606 Месяц назад
@@boopumer You'd use the same approach of pattern matching on the enum variants.
@filcondrat
@filcondrat Год назад
that reminds me of type classes in Haskell
@distrologic2925
@distrologic2925 Год назад
traits are basically type classes. There is a set of types that implement the trait, and generic functions can be written to accept any type implementing trait Noise, and then it can use anything from that trait.
@vikingthedude
@vikingthedude 10 месяцев назад
Typeclasses, traits, interfaces, protocols etc are all the same
@asdfghyter
@asdfghyter 9 месяцев назад
Rust’s type system is basically Haskell’s with added lifetime analysis, but without higher kinded types (meaning we can’t (easily) write traits for functors and monads).
@ZdenalAsdf
@ZdenalAsdf 8 месяцев назад
​@@vikingthedudeNot entirely. If you have two `Cat`s in languages like C# or Java, then they both could have different implementations of `Noise` because they might be arbitrary subclasses of `Cat`. That's one of the reasons why implementing binary operations in these cases is a bit weird and wonky - you get all the ` IComparable` weirdness which breaks once you start adding subtypes to it. However, C# now has static functions in interfaces, which do actually work more like type classes in Haskell and traits in Rust. The difference is that Java-style interfaces associate the implementation of the interface with an instance - each instance can have a different implementation. However, type classes/traits associate the implementation with a statically determined type, which is entirely different.
@shofr8475
@shofr8475 Год назад
You can simply make a trait and implement it to the enum instead of each struct
@brody9752
@brody9752 Год назад
but you cant specify different implementation for a trait on basic enums, they have to be structs
@electric26
@electric26 Год назад
You can also implement the trait for the structs themselves
@Cptcat.
@Cptcat. Год назад
that looks simple and easier to implement polymorphism.
@alvarozamora2679
@alvarozamora2679 Год назад
don't really need an enum. could use a marker trait or use the trait itself
@carlogustavovalenzuelazepe5774
Calm down im just starting learning this lol
@gamernecessario
@gamernecessario 2 месяца назад
i'm loving Rust reading the rust book
@TheOrioNation
@TheOrioNation Год назад
The problem I see most people coming from OO languages have with Rust is trying to shoehorn patterns intended to solve shortcomings of OOP, especially aspects of data modeling, and come to the conclusion that Rust isn't suited for such tasks. Rust is plenty powerful and easy to work with once you stop thinking in classes. Traits are not interfaces.
@samochreno
@samochreno Год назад
What do you mean traits arent interfaces?
@daishes
@daishes Год назад
but traits are interfaces? no? They work just like an interface does, it is a contract between the implementor and the interface that should be implemented, i don't get why it isnt an interface lel
@thegoldenatlas753
@thegoldenatlas753 5 месяцев назад
From the Rust Book. Note: Traits are similar to a feature often called interfaces in other languages, although with some differences.
@vanlepthien6768
@vanlepthien6768 Год назад
Interestingly, this is similar to some of the ideas I put forward in my PhD dissertation in 2010.
@IStMl
@IStMl 5 месяцев назад
ok
@philosophiabme
@philosophiabme Месяц назад
Link the arXiv? 😀
@friend7120
@friend7120 Год назад
I thought the "Rust lacks X, therefore X is inherently bad" thing was just a meme
@JeremyChone
@JeremyChone Год назад
No, but “X is inherently bad, therefore Rust does not have X” is one.
@tiredcaffeine
@tiredcaffeine Год назад
​@@JeremyChone Except inheritence isn't inherently bad. It is bad, like most things, when used incorrectly.
@friend7120
@friend7120 Год назад
@@JeremyChone Inheritance is inherently bad?
@gljames24
@gljames24 6 месяцев назад
​@@tiredcaffeineIt kind of is bad tho. Inheritance always has the diamond inheritance problem where you have undefined behavior from ambiguous inheritance. You also have to implement all methods even if they don't make sense. Using a trait or interface limited inheritance model allows you not only to have stricter control over what a type is inheriting compared to an object, you also are able to stucture the underlying data into an Entity Component System which allows for better memory access compared to an Object Oriented model.
@tiredcaffeine
@tiredcaffeine 6 месяцев назад
@@gljames24 Again, that's inheritence used wrong. If you inherit from two different classes that inherit from the same base class, then that's on you. If you choose a wrong base class to inherit from, then that's also on you. Read Circle-Ellipse problem. If you use inheritance correctly, it can be a really powerful tool. If you use it wrong, it will cause you headaches.
@NathanHedglin
@NathanHedglin Год назад
Inheritance, the shit we are forced to keep from our ancestors
@69k_gold
@69k_gold Год назад
Gold hahaha
@GreenDimka1
@GreenDimka1 Год назад
As much as ignorance, I guess
@MCRuCr
@MCRuCr Год назад
yes
@savire.ergheiz
@savire.ergheiz 8 месяцев назад
Then if its riches you should also be rejected them shit 😂
@Fikretov
@Fikretov 7 месяцев назад
Generational trauma for sure
@evols7028
@evols7028 Год назад
This approach breaks the Open-Closed principle. Although it can be achieved with dyn trait, it’s a very verbose, impractical, and developer unfriendly way to achieve it This is, for me, one of the biggest disadvantages of Rust
@woobilicious.
@woobilicious. Год назад
Open-closed is such a vague concept, if I had to guess you are trying to shoehorn OO design patterns into a non-OO language.
@MCRuCr
@MCRuCr Год назад
rust has to be verbose for the compiler to ensure the safety of your program. THAT is the main advantage of rust and the verbosity is a price I happily like to pay for that purpose
@Tibor0991
@Tibor0991 Год назад
​@@woobilicious. any language with structured data and interfaces is OO, deal with it.
@diadetediotedio6918
@diadetediotedio6918 Год назад
So, it doesn't break. Rust causes later implementations to occur at the trace level and this won't literally violate the principle, but I think you're using it in a place where it doesn't belong.
@TheOrioNation
@TheOrioNation Год назад
@@Tibor0991 That is a very liberal interpretation of what is OO. Data structures and interfaces are the basis of every language not at the assembly level.
@Lord2225
@Lord2225 Год назад
You can additionally use DeRef trait if you want all methods and fields from composed struct. It is handy if you want to build extension for other struct but still use it as before without outer.inner syntax.
@licks4vr
@licks4vr 11 дней назад
This literally just helped me build my rust program successfully
@jonathanadamsson6201
@jonathanadamsson6201 Год назад
It's very nice, I remember in some of my old game projects I would have several levels of inheritance, and hurts my eyes to look at that now. Then I started using interfaces more it was just more dynamic and allowed for better generic code. I feel like this works very similar to that, but more modular and just cleaner.
@JeremyChone
@JeremyChone Год назад
Same here. When we moved our backend from Java to TypeScript, we refactored to use many more interfaces than classes, and the code became more manageable. We still use some inheritance in TS, but very light. At first, Rust's hardline on no "data inheritance" was missing, but eventually, when using traits, generics, enums, and macros, those considerations do not come up anymore. Instead, the code becomes much more data-first focused, which is better for runtime purposes, as 80% to 90% of the code is statically bound (v.s. defaulting to dynamic dispatch), and interestingly, our code design improved as well. Win-Win!
@pickledeveloper
@pickledeveloper 9 месяцев назад
@@JeremyChonesure your program started faster but I highly doubt your TS is running at the same efficiency as your Java code, if it is, your Java was horrible.
@pickledeveloper
@pickledeveloper 9 месяцев назад
@@JeremyChoneI think you should rebuilt it in rust.
@JeremyChone
@JeremyChone 9 месяцев назад
@@pickledeveloper Ok, a few points: - "Rebuild in Rust" - It isn't about rebuilding existing projects, but utilizing Rust for the backend of our new projects. I'm even creating a video series and a dedicated website, [rust10x.com](rust10x.com), to share the production coding blueprints we are using. - "Java vs Node.js speed" - Being in the development field since the late '90s, we've traditionally viewed JavaScript more critically compared to Java, and for many good reasons. However, the period from mid-2010 to 2020 saw a significant shift, especially with the advent of Node.js and Google endorsing Node.js as a first-class citizen runtime. Although the V8 engine is technically slower than Java's JVM, the essentially async/NIO-based ecosystem leveled the playing field between the two, particularly for web app scenarios. To illustrate, when an app in a Node.js environment requires data from S3 and a database, the S3 command can be executed asynchronously. This was somewhat cumbersome to achieve with Java in the past. Therefore, while Java had the edge in raw speed, the overall performance became somewhat comparable when considering all aspects, including the easier integration of Node.js with docker/kubernetes environments. This shifted the focus towards developer productivity, where we found Node.js, coupled with TypeScript, to offer a more favorable environment. Now, all that being said, as mentioned initially, we are steering all our future development towards Rust, drawing from a decade of experience in production coding. You can find insights and guidelines on this transition at [rust10x.com](rust10x.com) and through my video channel. Thank you for the engaging discussion and your insightful points. Looking forward to more. Happy coding until the next time!
@cerebralgeneratedimagery5785
Inheritance means you can define an "Animal" struct and all animals(including pets) inherit eat, sleep and reproduce methods.
@mvnkycheez
@mvnkycheez Год назад
I think the problem is how much people simply use inheritance _wrongly_ , or where it isn't useful, rather than inheritance itself being a bad thing.
@ben.pueschel
@ben.pueschel Год назад
@@mvnkycheez The problem that most people have with inheritance isn't inheritance itself but what they first think of when they hear it: dozens of layers of abstractions and factory classes in the style of "modern" Java. But inheritance can be really elegant - if used correctly.
@theninjascientist689
@theninjascientist689 9 месяцев назад
And you can define an "Animal" Trait with default implementations for eat, sleep, and reproduce.
@zeez7777
@zeez7777 3 месяца назад
so again it boils down to being a skill issue and instead of admitting that people bash OOP
@edhofiko7624
@edhofiko7624 6 месяцев назад
i dont know about other, but i really like to call this programming paradigm of semi OOP with trait but no inheritance as Polymorphic Programming.
@aaronlink127
@aaronlink127 Год назад
I mean, there's a reason why most game engines and most AAA games make heavy use of inheritance and are written in C++. It allows for much easier code, especially if you have multiple types of something and want to write a more generic function that uses a parent. i.e, something like Grand Theft Auto makes heavy use of inheritance. For example, it could have a CVehicle class thats extended by CAutomobile, CHeli, CPlane, etc. Now, it could just tell a CPed to get into a CVehicle and it'll work on any vehicle type just like that. You end up with an expandable system that can accommodate any new vehicle type with ease. OOP is a good tool, and just like most good tools can be misused, but powerful if used properly.
@wlockuz4467
@wlockuz4467 Год назад
Not just games, most frameworks, platform SDKs like Android and iOS, game engines etc. use inheritance extensively and excel at it because the people who make them know what they're doing, unlike people who discredit features like inheritance because their favorite language doesn't implement it.
@beameyzed
@beameyzed Год назад
Uhm. I like C++ as much as anyone. But if I'm correct, a lot of modern engines (a lot not all) make use of ECS, a more data-oriented paradigm with minimal inheritance.
@Lord2225
@Lord2225 Год назад
Inherence is defiled and bad feature that leads to mistakes and bugs. Too bad it was popularized. The thing you are describing is polimorphism and it is one of the most important concept in programming. Rust archives goals of Inherence in modern and more flexible ways that are friendly for performance and developers. It decouples behavior (traits) and data (composing & DeRef)
@yokunjon
@yokunjon Год назад
Only reason they are written in C++ and adhere principles of C++ is because there were no performant alternative for so long, they had their tooling just for that. Also, what you say can be achieved with traits in Rust. You don't have to inherit a whole class implementation to do polymorphism or monomorphoism.
@aaronlink127
@aaronlink127 Год назад
@@Lord2225 I just dont see why you wouldn't want to inherit the structure in its entirety in a proper polymorphic setup. After all, you want them to share functions, and those functions usually also depend on properties on the class itself. Also makes the final assembly much smaller as it doesnt have to repeat code just to get the same value, but to be fair there is templating that will repeat sometimes. Then again, who cares about assembly size, you're using rust.
@jacobusburger
@jacobusburger Год назад
I’m just glad that people are finally realizing the value of functions and composition. Thanks for the video Jeremy.
@MCRuCr
@MCRuCr Год назад
yes so happy people are realizing oop is just a bunch of hot marketing air
@LuminaryGames
@LuminaryGames 11 месяцев назад
@@MCRuCr I prefer composition, but I like composition with oop, not functions.
@marcusrehn6915
@marcusrehn6915 Год назад
Is there any way to force all structs in the enum to have a trait implemented? So that if it gets removed from any of the structs, I can get a compile error.
@luizchagasjardim
@luizchagasjardim Год назад
If you remove a trait and the trait was being used, you will get an error anyway. If it wasn't being used, then no harm done. If you want something "more polymorphic", it would be "impl MyTrait" or "dyn MyTrait". That guarantees the type in question will implement the trait.
@CheaterCodes
@CheaterCodes Год назад
You can implement a trait on the enum, which you will likely do by matching on its variants and forwarding to a trait implementation on the inner type. This will obviously result in a compile error if one of the variants doesn't implement it.
@chinoto1
@chinoto1 Год назад
I like the idea of implementing Deref on an enum, with the target being the trait each variant should be implementing. If you need an example, remind me and I'll go find or recreate it.
Год назад
There's "behaviour inheritance", which is used for regular inheritance but in a controlled manner.
@ko-Daegu
@ko-Daegu Год назад
Go also doesn’t have inheritance, classes ..etc so was a nice experience to program with
@redcrafterlppa303
@redcrafterlppa303 Год назад
I think there should be a way to auto implement a trait for the whole enum when all containing types implement the trait. Bsp: Dog, duck, and cat implement noise. Then there should be a way to simply 1 line implement the trait for animal instead of needing a match that forwards the method to the individual versions.
@rurunosep
@rurunosep Год назад
Often when you think "there should be some way to do x", there's a crate that gives you macros to do it. I looked it up and found enum_dispatch, which seems to do just that. One line on the trait and one line on the enum.
@SbF6H
@SbF6H Год назад
Inheritance is useful. Ruling it out, seems like a whimsical decision. And it is made weird by the fact that Rust allows trait inheritance. Therefore it's effectively the same thing, except with traits (analogous to interface and virtual classes).
@cyrilemeka6987
@cyrilemeka6987 5 месяцев назад
People love to hate
@hadawardgz
@hadawardgz 5 месяцев назад
Thx for overcomplicating simple things rust, ily ❤
@JohnnySacc
@JohnnySacc Месяц назад
what's simpler than an enum?
@hadawardgz
@hadawardgz Месяц назад
@@JohnnySacc i mean, enum is meant to enumerate something, I meant to make it complicated but not difficult.
@krunalchauhan5780
@krunalchauhan5780 Год назад
Want more videos like this shorts ❤
@Mempler
@Mempler Год назад
In rust, i somehow always tend to forget about enums, that you can use it like a variant and emulate inheritance with it
@brians7100
@brians7100 Год назад
Rust enums are one of its best features
@wChris_
@wChris_ Год назад
How would you solve this problem: Imagine you have a sherd base class like a car, that has its position, velocity and acceleration. Now what you want to do is create inherited classes that all act differently by doing different things but still with a common interface. The point is that the base class may have lots of fields, and copying them for every subclass is error prone and can be buggy. From what i can tell rust excels at doing similar things on different data (imagine the classic shape polymorphism example), but kinda lacks at doing different thing with the same data (with a common interface for abstracting such operations).
@jakedewey3686
@jakedewey3686 Год назад
Define a struct to hold your common data attributes, create types or an enum that holds an instance of that struct, define a trait to define the common interface, and implement that trait on each type.
@NikolajLepka
@NikolajLepka Год назад
You'd either define traits that have default behaviour and polymorphic functions which use these traits. You then implement the traits for all the types you think need to be able to do these things
@mathgeniuszach
@mathgeniuszach Год назад
This is the only reason I haven't switched to Rust for most of my code; fields just aren't flexible in Rust. Some people see this as a good thing, and in some contexts it is, but in the contexts I find myself in, it is overly restrictive and leads to _less_ clean code. What people don't seem to understand is that it's not that Rust _can't_ do things like this, it's that it's not well suited for them.
@chinoto1
@chinoto1 Год назад
​@@mathgeniuszach As Jake and Niko have said: make a base struct with all the common fields and a trait for the behaviors, then make specialized structs with the base struct as one of its fields and implement the common trait as needed. Alternatively make an enum instead of (or in combination with via Deref) a trait and pattern match on each variant to get different behavior. The enum can be more efficient, but less flexible.
@mathgeniuszach
@mathgeniuszach Год назад
@@chinoto1 Literal quote: "What people don't seem to understand is that it's not that Rust can't do things like this, it's that it's not well suited for them." Macros ease the pain a bit (e.g., #derive), but it's just not clean otherwise.
@GreenDimka1
@GreenDimka1 Год назад
As a C# dev I miss inheritance. Most of the devs misuse it and then blame it. Composition is a way to organize data within classes while inheritance is a way to define classes ad-hoc.
@OcarinaOfVali
@OcarinaOfVali Год назад
as another C# dev, i agree
@asdqwe4427
@asdqwe4427 Год назад
Coming from the similar works of Java, I disagree. The only thing that is more useful than harmful in either of those languages as far as oop goes is interfaces. Checking if a type satisfies some condition. Extending classes brings implicit functionality with it. I can’t think of anything good that requires extending rather than implementing.
@GreenDimka1
@GreenDimka1 Год назад
@@asdqwe4427 probably you had very bad examples
@v01d_r34l1ty
@v01d_r34l1ty Год назад
@@asdqwe4427 You work with Java, that’s why. It’s OO out the ass. That’s probably its biggest flaw. Like all good things, moderation is key.
@raianmr2843
@raianmr2843 Год назад
You don't miss inheritence, you miss polymorphism - which Rust has decent primitives for. That said Rust doesn't operate in the same space as the likes of C# and Java, you're just not meant to push things to the runtime (even though you can) when writing Rust code. I would suggest you explore languages like Go, Julia, and Clojure. Go and Clojure demonstrate how not tying interfaces/protocols to inheritence hierarchies can achieve wonders and Julia and Clojure together show how multiple-dispatch solves all the problems inheritence does and more.
@CTimmerman
@CTimmerman Год назад
So a van has a car base and honk trait like the car as well.
@nikozdev
@nikozdev 9 месяцев назад
You’ve just gave me another reason to invest my time into this lang 😅
@travelan
@travelan Год назад
Why is this a cold shower we “all need to take”? What is this rebellion agains OOP? I only hear subjective arguments from Rust enthousiast. The best being that ‘it is often used wrong’. By that sense, any programming paradigm is a bad idea.
@Lestibournes
@Lestibournes Год назад
To summarize the linked article: inheritance causes subclasses to break when super classes change.
@travelan
@travelan Год назад
@@Lestibournes Rust code will break just as easy, when depending code changes. What is the point?
@Lestibournes
@Lestibournes Год назад
@@travelan the point of the article is that using encapsulation + interfaces instead of inheritance can prevent many cases of breakage while still achieving the same desired result.
@MCRuCr
@MCRuCr Год назад
@@Lestibournes 👍
@Tibor0991
@Tibor0991 Год назад
Typical Rustacean ignorance, they think Rust is not OOP just because it has "flat" inheritance (i. e. an object can only inherit one or more interfaces, but can't inherit further), but flat inheritance is the de facto standard in modern C++.
@vashlex
@vashlex 4 месяца назад
Thats not a big problem, I do dislike the cryptic names of Rust library types though. Or will any no-rust developer ever guess what Arc should be used for without reading the docs. And there are more examples to this.
@JeremyChone
@JeremyChone 4 месяца назад
Choose physics over cosmetics. Taste changes, physics don't.
@vashlex
@vashlex 4 месяца назад
@@JeremyChone In my opinion good names are essential and also do not fall into taste. Especially because you can not refer to Arc as a name but an acronym. Maybe this acronym is well known to some people outside Rust, at least to me it is not.
@user-hy5cx9iu3l
@user-hy5cx9iu3l Месяц назад
If you are non-rust dev you realy don't need to know what is Arc. Besides, try to code any script dyn type lang without reading docs😂😂😂
@leonidasiii2857
@leonidasiii2857 Год назад
I love Rust and I love traits. HOWEVER, I have found that in the realm of unit testing, mocking is a bit of a pain in Rust without inheritance. If you want to mock a struct and swap it out while running tests, good luck. Instead, you have to hide every single struct behind a trait which just adds a ton of "fluff" to your code. In this specific case, I reeeaallly wish Rust had inheritance as an option and just didn't recommend it otherwise.
@vas_._sfer6157
@vas_._sfer6157 Год назад
If you want to replace struct, you must use a trait. The structs - is only about data, not OOP objects. If you have struct Person it is only Person, not null, or children.
@leonidasiii2857
@leonidasiii2857 Год назад
@@vas_._sfer6157 yup, that's exactly what I'm saying. But because structs are not objects and can't be mocked, unit testing can be a pain in Rust.
@vas_._sfer6157
@vas_._sfer6157 Год назад
@@leonidasiii2857 It is not a bug. It is feature. Struct is always a concrete types. If we need a mocking we must use traits. If we have to moke network querry, we can use SomeStruct (N is empty struct that implement our Network trait with some methods). And now, we can mock a network (SomeStruct). And generic it is not a problem we can use a 'use' keyword.
@leonidasiii2857
@leonidasiii2857 Год назад
@@vas_._sfer6157 I'm aware that it's intended, and I'm aware of how to get around it 😂 What I'm saying, is that in this specific case, it's a pain and inheritance allows for cleaner more intuitive code than traits
@r1nlx0
@r1nlx0 Год назад
You never need (using mock) to do this in practice, you just need to implement traits that you want to be as a dummy. Most of cases, you either go property tests or implement an instance of the traits, by this, it also promote granular way of designing behavior through trait systems.
@cinderwolf32
@cinderwolf32 3 месяца назад
Love Go for this.
@gianglaodai107
@gianglaodai107 Год назад
So in Rust we use product type and sum type, right
@oriolesteve4634
@oriolesteve4634 22 дня назад
c++ -> std::variant and visitor pattern
@morglod
@morglod 5 месяцев назад
Mmm switching by typeid with match instead of static methods through templates That rust genius coders
@markcoren2842
@markcoren2842 7 месяцев назад
As a former polymorphism fanatic, I've absolutely loved diving into Rust. Thankfully I'd broken my addiction a while ago, but Rusty took things in a beautiful new direction for me.
@bravo________87372
@bravo________87372 Год назад
Or make them implement a pet trait
@awiteb
@awiteb Год назад
You can use traits and make it easier
@SP-db6sh
@SP-db6sh Год назад
make a video for python codes interested to learn Rust .... simple steps with basic projects.... so they can continue
@JeremyChone
@JeremyChone Год назад
Yes, this is on my todo list. Python to Rust, and JavaScript/TypeScript to Rust.
@phatkin
@phatkin Год назад
The one thing I wish Rust had is Go's syntax sugar for struct composition.
@jaxica476
@jaxica476 Год назад
I wonder if you can do that with macros hm
@freshouttathebag7725
@freshouttathebag7725 2 месяца назад
Go needs something like this so fucking bad
@riceartfilms
@riceartfilms Месяц назад
I do miss Enums in Go, but i believe Interfaces do a good job
@atesztoth
@atesztoth Год назад
Love it!
@unduloid
@unduloid Год назад
Actually, it makes more sense to have a Cat or Dog have a reference to a Pet. Just sayin'.
@JeremyChone
@JeremyChone Год назад
Yes, there are many ways to skin the cat. You could have Pet with .kind attribute which would be an enumeration with Cat, Dog, Snake, … variants.
@SHuRiKeN1812
@SHuRiKeN1812 4 месяца назад
This reminds me of Nathan Stocks’s description 🤔
@tiagodagostini
@tiagodagostini Год назад
Yet it is a pain in the ass for people that knew when to use one and other and used (in C++ ) protected inheritance to create automatic composition by template assignment.
@py0n34r
@py0n34r Год назад
Wow this was a really easy way for me to understand inheritance, thanks!
@ccgarciab
@ccgarciab Год назад
This is not inheritance, that's precisely the point of the short: using composition instead of inheritance.
@collynchristopherbrenner3245
@collynchristopherbrenner3245 7 месяцев назад
Is this comparable to discriminated unions, except using an enum instead of a parent union type?
@JeremyChone
@JeremyChone 7 месяцев назад
Yes, with sum types. Enums are often referred to as Algebraic Data Types (ADT).
@skidkadda
@skidkadda Год назад
guess they favour composition over inheritance, which isn't all too bad
@gerardzinn
@gerardzinn 4 месяца назад
Theme?
@wassim-akkari
@wassim-akkari 16 дней назад
And that's how it should be, I love rust because like me we both think that evloution is a scam
@MrG0olden
@MrG0olden Месяц назад
I wish Go had Rust enums
@JBroMCMXCI
@JBroMCMXCI 9 месяцев назад
How long until we get Rust++ with inheritance?
@at-sushi
@at-sushi Месяц назад
in OOP, changing of class inheritance is a nightmare.
@Labicraft
@Labicraft Год назад
Isn't that quite appalling doe? You literally have to maintain an Enum and manually make sure that every Pet has all the traits implemented... Even if inheritance is usually not the answer it can still be useful for some things...
@voxelfusion9894
@voxelfusion9894 Год назад
Shh, the rustaceans haven't gotten that far yet, the compiler won't let them get past the memory allocation.
@stratospheregaming114
@stratospheregaming114 Год назад
You can implement traits on enums, you just need to pattern match the different concrete types. Or you can use a general case match if multiple types perform the same behavior for a trait
@rurunosep
@rurunosep Год назад
You can use a macro from the enum_dispatch crate to generate the enum code in a single line. The enum will implement the trait by just delegating to the struct inside the variant. Good example of how macros make the whole language extensible. This will still require you to implement the trait on every struct, making the enum act like an abstract class. I'm sure there are crates providing ways to concisely emulate more OOP features if you really want that and just look it up. It's moving away from idomatic Rust, but if you feel that "inheritance is still good for some things", someone agrees with you and has already made a solution.
@rurunosep
@rurunosep Год назад
@@voxelfusion9894 You literally can allocate memory just fine. You just wrap the operation in an unsafe block. Sounds like it's you who hasn't gotten past even the basics of the language before you tried to clown on others.
@mskiptr
@mskiptr Год назад
Imo inheritance is generally a bad idea. Interfaces (Rust traits | Haskell typeclasses) together with ergonomic unions (Rust enums) result in much more reasonable code. From what I can see, the only place inheritance (and object-oriented design) makes any sense is when you're simulating a bunch of distributed agents.
@parallellinesmeetatinfinity
😮
@spaghettiking653
@spaghettiking653 10 месяцев назад
Isn't traits extending other traits inheritance?
@JeremyChone
@JeremyChone 10 месяцев назад
Inheritance typically means you inherit the properties as well.
@spaghettiking653
@spaghettiking653 10 месяцев назад
@@JeremyChone I see, that makes sense.
@niks660097
@niks660097 Год назад
No inheritance!?
@CreateCG1
@CreateCG1 Год назад
Execute this Num1 = n Num2 = c Num3 = i Num4 = e Print(Num1, Num3, Num2, Num4) All in python
@Divino_1
@Divino_1 Год назад
Rust is the only language that is being forced down my throat.
@tobytragen4363
@tobytragen4363 Год назад
Everyone is telling me to try it and it feels like it is cornering me
@ccgarciab
@ccgarciab Год назад
❄️
@azhagurajaallinall126
@azhagurajaallinall126 Год назад
Feels like the same way Java marketed to deep dowm its roots to legacy companies & every tech stack that been forced by managers,because they felt so (like falling into scam 😅) 23.11.2022 01:34 am ist
@wlockuz4467
@wlockuz4467 Год назад
Glad I am not the only one.
@Tibor0991
@Tibor0991 Год назад
Same. Can't go one day without RU-vid peddling me Rust content.
@crazyingenieur3277
@crazyingenieur3277 2 месяца назад
In this example, if we would like to have a new pet called Bird, wouldn't we have to modify the enum Pet to add the new Bird(Bird) variant?? Instead, why don't we have a trait called Pet and move the `noise` function into this trait? And we no longer need the Noise trait. Then in order to have the new pet Bird, we would just create a new struct called Bird and impl Pet for Bird... and we would not be changing anything that already exists. The solution with enum Pet to me is not extensible because we would have to modify it for each pet we add in the future.
@JeremyChone
@JeremyChone 2 месяца назад
You could definitely make a `Pet` or `PetBehavior` trait, and then rely on trait objects and dynamic dispatch, which is also a valid approach. Both ways are, in fact, complementary, as you can still have your `Pet` enum that would implement `PetBehavior`, and then you get the static dispatch as well. So, you can have it both ways.
@Ar7hurz1nh0
@Ar7hurz1nh0 Месяц назад
While you could do this, its important to know the performance tradeoffs. By using an enum, the compiler can know at compile time the maximum/minimum size of the returning type, and can use stack memory to do so. By implementing this using a trait, we may lose this compile time behavior, and thus the compiler may end up using a runtime based alternative (especially if you use a return type like `Box`), that will use heap memory. Its a tradeoff between performance and extensibility, but it may end up only mattering if you do this hundreds to millions of times during execution
@thewilltejeda
@thewilltejeda 7 месяцев назад
Lol @cold shower 😂
@mzg147
@mzg147 Месяц назад
It would be better for Pet to be a trait...
@JeremyChone
@JeremyChone Месяц назад
There are different ways to skin a cat.
@Zeero3846
@Zeero3846 Год назад
When I learned Haskell, I realized functional classes was exactly what inheritance was trying to do but OOP made you do it badly.
@Terminaleki-ih1ln
@Terminaleki-ih1ln Год назад
traits
@gmodrules123456789
@gmodrules123456789 Год назад
So it basically achieves the same thing, but with different syntax? I can see some good uses, but why no option to do traditional inheritance?
@MCRuCr
@MCRuCr Год назад
because giving multiple tools for the same purposes results in chaos and frameworks wont be able to work with each other. every language should have exactly one concept to address each of a programming languages requirements (like encapsulation, interfacing, composing data, ...)
@fortwentiblazeit4177
@fortwentiblazeit4177 8 месяцев назад
OO developers discovering Typeclasses for the first time
@chinoto1
@chinoto1 Год назад
How to mimic inheritance in Rust if you really want to for some reason: Make a base struct, a trait, and impl the trait for the struct. Now make a struct with one of its fields being the base struct and impl the trait, calling the base struct's impl where needed. I haven't done this myself, so let me know what downsides you find with this.
@JeremyChone
@JeremyChone Год назад
You can get some basic inheritance characteristics at a high level with traits and "blanket implementation," but you won't get far (e.g., override, overwrite, ...). However, I recommend not mimicking inheritance, embracing the Rust language, and going with composition using struct, enum, and traits. Also, there are many great language constructs and patterns using From/TryFrom, monomorphization, and macros. Once you get the hang of them, the code gets very componentized, relatively DRY, and fully optimized. It took me a while to rewire my brain from traditional OOP, and while I still use it when coding TS/JS, I do not miss it anymore when coding Rust (which is most of my coding those days).
@MCRuCr
@MCRuCr Год назад
@@JeremyChone overwrites of methods are total bs to begin with. it defeats the purpose of inheritance
@Merthalophor
@Merthalophor Год назад
The downside is that you inplement every single method again!! You can use Deref tho, but that's a bit abuse of the idea of deref.
@chinoto1
@chinoto1 Год назад
@@Merthalophor Yeah, that could be a nuisance, even if it's just `fn foo(&self) {self.base.foo()}`. I haven't done much with extending classes or anything else involving inheritance.
@trejohnson7677
@trejohnson7677 Год назад
I suppose this is a win for the ontologically challenged.
@legitjimmyjaylight8409
@legitjimmyjaylight8409 Год назад
this is strateg pattern. The enums I dont like, because if you have many classes that "inherit" another, you got to keep going back to this, and the Parent class has to know about all its children, but a parent shouldn't need to know about any of its children. That is really bad coupling.
@techsupport1294
@techsupport1294 Год назад
Haskell does it better with typeclasses. Much more elegant.
@NikolajLepka
@NikolajLepka Год назад
traits are type classes
@HansBezemer
@HansBezemer 24 дня назад
Basically, a class is nothing but a struct with some function pointers that are initialized when instantiating. You can even do that in C if you want - using some dirty preprocessor tricks. So don't pat yourself on the back. The problem is not with OOP languages, the problem is with the very concept of OOP, which opens the door to "lasagna programming". If you think you can create good programmers by forbidding anything you consider "bad practice", you might want to catch up on what Edsger Dijkstra had to say about that.
@JeremyChone
@JeremyChone 23 дня назад
First, thank you for sharing your perspective. Second, if Edsger and you have productive patterns that allow you to build robust and efficient programs with more traditional languages, it's completely fine. From my experience, having written relatively big apps for many years in many languages, I can share that for my style of programming, Rust really hits the nail on the head. Somehow, its constructs and constraints entice us (my team and I) to design code in a more robust and future-proof way. I can see this when I come back to a code I wrote six months ago; it's so fast to add features or fix bugs. Personally, I do not believe in absolute truth. So, there might be other languages or patterns that can be very efficient for other developers. I am just sharing that for my team(s) and me, Rust allows us to write more robust code faster (after the initial learning curve), with an appreciable bonus on speed and memory efficiency. Happy coding!
@LYVFX
@LYVFX 8 месяцев назад
cool
@tilin7518
@tilin7518 Год назад
Puso "," y luego cerró llaves, eso no es error?
@JeremyChone
@JeremyChone Год назад
Trailing comma is ok in Rust.
@tilin7518
@tilin7518 Год назад
​@@JeremyChone That could be bad programming practice
@user-hy5cx9iu3l
@user-hy5cx9iu3l Месяц назад
​@@tilin7518 actually it's opposite.
@supremedeity9003
@supremedeity9003 8 месяцев назад
Tsoding coding in rust is kinda... ironic.
@itguruwithpowers
@itguruwithpowers 4 месяца назад
Traits
@JeremyChone
@JeremyChone 4 месяца назад
Not same
@cursedfox4942
@cursedfox4942 24 дня назад
That’s almost exactly c++ lmao barely a seperate language lmao
@dealloc
@dealloc Год назад
Ban the keyword "extends" or whatever syntax your language uses to inherit logic from each other, and replace with interfaces. Compose your objects with interfaces. Results in a flat hierarchy that is easier to reason about and refactor and adapt. Nested concepts are hard and time consuming to unnest; you either end up with duplicate code anyway, or in worst case, you end up having to refactor everything from top to bottom. Keep your objects more specific, and your interfaces more generic. But don't overthink it. Avoid prematurely abstracting your code. For example: a "Shape" is too generic for an object, but is generic enough for being an interface. A "Rectangle" is too specific to be an interface, but specific enough to be an object. An interface can add additional constraints, depending on its requirements. For example, we could consider a "Shape" to have a dimension, transform and be rendered onto a canvas. So it can implement other interfaces like "ITransform, IDimension, IRenderable".
@disabledmallis
@disabledmallis Год назад
Thats just interfaces from java...
@NikolajLepka
@NikolajLepka Год назад
it's not! Traits can have default implementations. It's closer to abstract classes which can be inherited multiply + a mechanism to handle the diamond problem
@JeremyChone
@JeremyChone Год назад
Java interfaces can have default implementation as well.
@pyyrr
@pyyrr Год назад
well, they say rust accidentally fixed all the problems that every language has
@donwinston
@donwinston 5 месяцев назад
I don't think so. Composition. works well much of the time but inheritance is a beneficial feature. It is not something that always should be avoided.
@user-hy5cx9iu3l
@user-hy5cx9iu3l Месяц назад
Can we inherit a square from a rectangle?
@astrahcat1212
@astrahcat1212 Год назад
C# I never use inheritance, I thought I was being amateurish this whole time until hearing all the talks about procedural programming. Then I remembered that the beginning programming languages I had learned in the 2000s weren’t object oriented, mainly C, and this strange game development one called DarkBasic Pro
@sacredgeometry
@sacredgeometry 4 месяца назад
Inherence is great ... when you use it for what its supposed to be used for ... which is not code reuse. i.e. if composition/ the strategy pattern solves the problem you are facing with inherence you are doing inheritance wrong. Inheritance is for establishing known and immutable type hierarchies. Nothing else. If you really need to force yourself to not be bad at programming a lot of languages allow you to establish those type relationships using interfaces/ protocols which explicitly dont allow for implementations. Taking them out of the language completely is just admitting your are too dumb to be allowed off training wheels and you think that other people are as dumb and cant be trusted. Its cute but no thanks, you have fun playing in the sand pit I will keep my language features.
@v-for-victory
@v-for-victory Год назад
Abstract classes? Anyone?
@sunpoke5317
@sunpoke5317 Год назад
Why would you need abstract classes in this case?
@v-for-victory
@v-for-victory Год назад
@@sunpoke5317 Did I said in this case?
@BuFu1O1
@BuFu1O1 Год назад
Protocols
@milanpanic3755
@milanpanic3755 Год назад
So rust doesn't have inheritance, and now inheritance is considered bad? Enums can be used incorreclty too. And I've seen it happen more than inheritance.
@welltypedwitch
@welltypedwitch Год назад
I never really liked this explanation. Sure, in this specific case, you can use enums instead of a common interface, but it's not equivalent in general. The entire point of interfaces is that they are *open*. You can always add new implementations later without changing code. This is absolutely not the case with enums. Also, Rust has a great way of handling open "interfaces": Traits! If you wanted something that was as least as powerful (more powerful actually!) as the OO solution for this, you could just have a Pet trait that specifies the Animals' shared behaviour and implement it for each one.
@JeremyChone
@JeremyChone Год назад
Traits are for behaviors not data (i.e. properties). In Rust, you cannot inherit properties.
@welltypedwitch
@welltypedwitch Год назад
​@@JeremyChone You don't (well, shouldn't) abstract over data though. If you want to write a function that works on Pets, you are going to write something that is generic over the behavior of that Pet, not the data it stores. If that behavior includes "get the name of the Pet", then you can still have a method for that, which just looks up the field. Traits are great at this. This is exactly why it's usually considered a best practice in OO to write getters/setters, so that class fields are not exposed.
@JeremyChone
@JeremyChone Год назад
Not sure, but if those patterns work for you, great. Happy coding!
@JeremyChone
@JeremyChone Год назад
By the way, I would agree that this Pet example was just an illustration to make it short and sweet. Depending on where we want to go with this, we might want to start with an enum or a struct and treat the data variants down the structure. With traditional OO languages, you can inherit data (i.e. Properties), behaviors (interfaces & class methods), and annotations (e.g., in Java). In Rust, you do not have the "data inheritance," so you have to structure your data relationships differently with a combination of Struct/Enum. I think it is for the better, but it takes some brain rewiring. Traits are for behavior componentization and should be used accordingly, but they are solving a different problem. As of now, I think that by being "data first" Rust has picked the right angle to build an expressive language while being very close to the machine constraints, giving us back maximum performance and data integrity.
@mariolis
@mariolis 6 месяцев назад
Is this a medieval setting when slavery still existed or a dystopian present/future where slavery still exists ?
@chudchadanstud
@chudchadanstud 8 месяцев назад
That's great, now try building an actor framework. Wrapping things in enums simply become unmanageable as the project scales
@JeremyChone
@JeremyChone 8 месяцев назад
Actually, quite the opposite: ADTs are quite useful for typing and scaling the message part of an actor pattern.
@ari_archer
@ari_archer Год назад
in rust, you don't write code, you actually spend 10 hours hunting down dependencies (bc you need at leadt 10000 per LoC), obsessiong over random things and ofc compiling for 9 h/LoC, fighting the compiler too
@mannycalavera121
@mannycalavera121 Год назад
Don't use it then
@yokunjon
@yokunjon Год назад
No I don't, anything else?
@ari_archer
@ari_archer Год назад
@@yokunjon no
@wChris_
@wChris_ Год назад
unfortunately most of my computer science course revolves about inheritance, because of things like encapsulation and separation of concerns. And if you work in a company you most likely are modeling your code (with UML but also) with inheritance.
@gmodrules123456789
@gmodrules123456789 Год назад
I don't think I've ever seen a UML diagram used.
@Stopinvadingmyhardware
@Stopinvadingmyhardware Год назад
I want a framework written in Rust, for Python and Julia.
@christianm4906
@christianm4906 6 месяцев назад
Not having inheritance somewhat inclines me to consider other programming languages. There are numerous design patterns that work effectively with inheritance. Additionally, in other programming languages, I can utilise both inheritance and composition, as well as abstract classes and interfaces. Therefore, why would I want to relinquish such flexibility for the sake of using a niche programming language like Rust, merely due to its hype? No thanks.
@anotherelvis
@anotherelvis Месяц назад
A trait is basically an interface
@KingCroissant
@KingCroissant Год назад
Or you can use trait objects
@nikolagrigorov3210
@nikolagrigorov3210 Год назад
If I can't program on my mobile phone a program that updates a classic text file (ie to save collected own parameters: position, datetime, image,...), then RUST and other programming languages ​​are useless. It would be good if the HTML calls the JAVA script, and this one of the programs that the manufacturer can code in machine code, if not in the programming language you promoted. -> I am trying to open a test file in javascript and write records. That is, I am trying to have my mobile phone collect data completely independently of the network and save it in one of the files. At the same time, it is also important that the phone is also an independent developer, i.e. a programming platform with its library of routines that can be used at any time to create new programs.
@theninjascientist689
@theninjascientist689 9 месяцев назад
I have read this at least 5 times and can't seem to make heads or tails of it. What exactly are you trying to do?
@nikolagrigorov3210
@nikolagrigorov3210 9 месяцев назад
@@theninjascientist689 I am trying to open a test file in javascript and write records. That is, I am trying to have my mobile phone collect data completely independently of the network and save it in one of the files. + At the same time, it is also important that the phone is also an independent developer, i.e. a programming platform with its library of routines that can be used at any time to create new programs.
Далее
How does Rust make me write GOOD CODE ?
3:18
Просмотров 13 тыс.
Cabeças erguidas, galera! 🙌 Vamos pegá-la!
00:10
Просмотров 669 тыс.
Conquering fears and slippery slops on two wheels!
00:18
Who has won ?? 😀 #shortvideo #lizzyisaeva
00:24
Просмотров 2,1 млн
Enums considered harmful
9:23
Просмотров 197 тыс.
The Flaws of Inheritance
10:01
Просмотров 907 тыс.
Rust - spawn_block optimization for Argon 2
3:11
Просмотров 2,1 тыс.
Interview with Senior Rust Developer in 2023
9:46
Просмотров 655 тыс.
Torvalds Speaks: Rust's Impact on the Linux Kernel
3:50
Rust Quick Refactoring Trick (Rust Programming Tips)
2:27
Why You Shouldn't Nest Your Code
8:30
Просмотров 2,6 млн
Rust AI Developer: Creating a Devin Clone
6:56
Сложная распаковка iPhone 15
1:01
Просмотров 14 тыс.