How rust forces you to respect memory

Поделиться
HTML-код
  • Опубликовано: 20 окт 2024
  • (Insert standard disclaimer here about how this is just dipping your toe into the tip of the smallest part of the iceberg that is rust)
    I've been reading a lot about rust lately and having a lot of fun. It really has a lot to offer. So who knows, maybe there will be more rust software development in the future. But for now this is my introduction to learning rust.

Комментарии • 72

  • @DuskyDaily
    @DuskyDaily 11 месяцев назад +33

    This is amazing but not the main reason why most people love Rust. Rust like used all the good practices that have been developed by the programming community and fit into a single language, almost each Rust feature could be a reason of its own to like it. The compiler errors are amazing. Rust Enums featuring algebraic type system, offering amazing error handling system with Result type. No null values with Option types, completely eliminating an entire field of problems. It isn't object oriented but still have interfaces (known as traits) and type methods, but no inheritance (which was like the part used badly in other OO languages). And I could just go on and on. Rust took all good parts from different languages, coding styles and paradigms, but removing the bad parts about em. Rust is arguably the best one yet, still not perfect and still improving.
    And personally I found Rust as the best middle ground from "close to procedural" but still very expressive with functional programming paradigm.

    • @lavonov
      @lavonov 21 день назад

      I completely agree, rust is a language designed by experience

  • @danilfun
    @danilfun 11 месяцев назад +59

    Big thing missing from the video is C++ objects, which could also be automatically destructed, could also be moved, could also be referenced. It's also free.
    On the first glance it seems like rust is no better than C++.
    Critical missing information here is that rust enforces these constraints, while C++ does not. I think this is the main reason why rust is better, object ownership is secondary.

    • @indiesigi7807
      @indiesigi7807 10 месяцев назад +7

      I just don't consider safer as better. it's such a reductionist view. c++ is better in every way except in explicit safety. People are gonna write horrible code thinking it's safe and efficient and it's most likely not. Enums are an example where the largest variant will dictate the allocated size per entry. It looks very elegant but it's the opposite of efficient. Rust is full of this and you need to know and be mindful about it or you'll write the most bloated inefficient programs ever. If rust picks up brace yourself for mountains of truly horrible code with a certified quality label.

    • @angelcaru
      @angelcaru 6 месяцев назад +7

      @@indiesigi7807 How are enums the opposite of efficient? For that usecase, you WILL need to use the maximum variant size (unless you want to suffer with malloc). The direct translation to C/C++ has the same problem:
      ```rust
      enum E {
      A(i32, i32),
      B(u64, u64)
      }
      ```
      ```c
      typedef enum {
      E_A,
      E_B,
      } E_Type;
      typedef struct {
      E_Type type;
      union {
      struct { int a_first, a_second };
      struct { uint64_t b_first, b_second; }
      };
      } E;
      ```

    • @mk72v2oq
      @mk72v2oq 3 месяца назад +4

      The main feature of Rust is the borrow checker.
      C++ has unique_ptr and shared_ptr, which are analogous to owned value and Arc in Rust, but that's where C++ safety ends. In C++ invalid references are allowed, you can have multiple mutable references, can hold reference to a no longer existing value etc. C++ doesn't have any mechanism to avoid it. That's why things like use-after-free are so common in C++.
      Rust does provide safety guarantees for references. All references are always valid, you can't have multiple mutable references, references can't outlive values. That's why it's practically impossible to produce memory-related bugs.

    • @Sacred-Lotus
      @Sacred-Lotus 27 дней назад

      ​@@mk72v2oqVery Good explanation. I can see why rust ensure memory safety:only *One* immutable Reference is allowed for each Object/Functor. They will be destroyed when the ref counting reaches *Zero* (I.e. Ref to obj no longer in use).

  • @hcn6708
    @hcn6708 4 месяца назад +7

    "Ok, so hear me out on this: Rust" _mixed reaction from the crowd_

  • @pitbul2877
    @pitbul2877 11 месяцев назад +13

    reminder that you don't have to do the (int *) malloc anymore, void pointer gets automatically promoted to whatever you assign it to

    • @scrambledmandible
      @scrambledmandible 11 месяцев назад +1

      Is it not a safe pattern to keep using though? Just in case, you know

    • @pitbul2877
      @pitbul2877 11 месяцев назад

      @@scrambledmandible it works this way ever since ANSI C so unless you're compiling on something really old it's just redundant. One argument for doing it, actually, is for C++ compatibility apparently? idk, there's no real advantage to either, but one clutters the code so it's just a bad practice in my opinion

    • @deadmarshal
      @deadmarshal 7 месяцев назад

      I C it's ok, but in C++ casting is needed@@scrambledmandible

    • @marcossidoruk8033
      @marcossidoruk8033 2 месяца назад

      ​​@@scrambledmandible No. Assigning a properly aligned and valid void* to an int* is perfectly safe and adding an explicit cast does nothing really.

  • @pshr2447
    @pshr2447 11 месяцев назад +14

    So doesn't Smart Pointers in C++ also solve this particular problem of memory leak when variables are going out of scope? Like if we have a pointer and enclose it in a class then if it goes out of scope it's destructor will be called which will initiate the cleanup code required to free up the memory. Is it not a good enough solution or am i missing something?

    • @alvaroluis5368
      @alvaroluis5368 11 месяцев назад +9

      Not only smart pointers. std::vector is basically an array of variable length in heap that gets freed when out of scope. It is also used in std::string and in every class that frees up resources on its destructor. It's called RAII and it was a thing in c++ before Rust existed.

    • @mghinto
      @mghinto 5 месяцев назад +6

      C++'s safety is an afterthought and is all opt in, while Rust's safety is inherent to the language and is all opt out. That makes a big difference and reduces what code you have to consider when something goes wrong. Also, if your rust program compiles, you can be pretty confident that it will work before you even run it.

    • @starllama2149
      @starllama2149 3 месяца назад +4

      @@mghinto I don't get this mindset though? Nobody is forcing you to use the unsafe c++. Nobody is also forcing you to not use the unsafe keyword in rust. C++ is plenty fine enough. RAII is enough.

    • @jcm2606
      @jcm2606 4 часа назад

      @@starllama2149 The problem is that RAII in C++ is not mutually exclusive to the old ways of doing things. Modern C++ still allows you to freely allocate memory using malloc/new, modern C++ still allows you to get a raw pointer from a smart pointer, modern C++ still allows you to mutate a value through _any_ pointer pointing to a non-const value, smart or not. You may scoff and say something along the lines of "anybody who knows what they're doing wouldn't do this", and yes, you're right. The problem is not everybody knows what they're doing, and even those who know what they're doing can have a lapse in judgement and make a mistake somewhere that proliferates and leads to swaths of unsafe code. It's not enough to just trust that everybody and anybody knows what they're doing, which is what Rust understands and IMO gets right with its safe-by-default design.

  • @darrellplank4518
    @darrellplank4518 10 месяцев назад +6

    Generally well explained but left out are the MANY corollaries of Rust's philosophy such as standing on your head to get two objects that point to each other and the difficulties inherent in graphs. That you have to drag in special crates just to have a mutable global. New concepts entirely like lifetimes need to be understood, etc., etc.. I realize there are solutions to all this, but Rust requires a lot more out of the programmer than C++ does - it just does. I also realize that most Rust programmers would say that's a good thing and most of the time I'd be with them on that opinion, but to leave all this out will really not describe to a C++ programmer the difficulty of adjusting to Rust. This makes it seem like ownership is a no-brainer and "that's all there is" when, in fact, the devil's in the details.

  • @pshr2447
    @pshr2447 11 месяцев назад +2

    Great video btw actually made me so curious that i would like to learn more about rust

  • @ErikBongers
    @ErikBongers 7 месяцев назад +3

    Nitpicking, but rust wouldn't pop arr from the stack after the move. It's the compiler that marks arr as no longer valid. It's a compile time check, not a runtime action.

  • @yazode
    @yazode 11 месяцев назад +1

    Thank you for the great video!! what software do you use to make such illustrations?

  • @MikeDawson1
    @MikeDawson1 11 месяцев назад +5

    isn't this just like an std::vector though?

  • @tru2thastyle
    @tru2thastyle 3 месяца назад

    It can’t be the best unless it does all that, but was simple. Instead it’s complex with a steep learning curve. That’s not a small issue, people don’t run companies don’t understand the value of being able to move quickly.

  • @CliveStewart-bq3od
    @CliveStewart-bq3od 6 месяцев назад +1

    Very clear and understanding .. you must do more videos like this

  • @whereispie
    @whereispie 4 месяца назад +1

    Awesome, thanks

  • @SamualN
    @SamualN 4 месяца назад

    how does this apply when using async though?

  • @maelstrom254
    @maelstrom254 11 месяцев назад +6

    C++ works exactly as described in the video 😂

  • @shadergz
    @shadergz 11 месяцев назад +5

    C++ Smart pointers: I don't exist**

  • @alvaroluis5368
    @alvaroluis5368 11 месяцев назад +15

    This concept is called RAII and you could do it in C++ years before Rust existed

    • @adityatripathi9125
      @adityatripathi9125 Месяц назад +6

      yes, infact Rust borrowed it from C++ but the fact that Rust has it as a 'default' mechanism it what is better (and safer) IMO.

    • @sot_dev
      @sot_dev 9 дней назад +3

      right, but you might forget to handle this in C++ unlike Rust it's done automatically

  • @codersanInHoodie
    @codersanInHoodie 15 дней назад

    what is stopping java from implementing this?

  •  11 месяцев назад +9

    Surely it is because I’m an old fashioned C/C++ programmer and I can’t still see the beauty of this ownership paradigm, but right now I can only think about how annoyingly painful would be for me to try coding about anything in Rust, I already have a headache just from thinking about it.
    I can definitely see the advantages of of the compile time analysis and strict memory management Rust provides, but I’m afraid it comes with a cost in flexibility and usability that may be too high for certain situations.

  • @zeropointer125
    @zeropointer125 11 месяцев назад +6

    Wait... but c++ does pretty much the same things. Only difference is = copies by default and you have to explicitly std::move

  • @Valerius123
    @Valerius123 2 дня назад

    Rust did not introduce the concept of ownership. It's just the first performance based compiled language to come out in a long time that *also* facilitates ownership. And what... do you think you get this all for free? What you're sacrificing is the overall design and maintainability of your program since you become burdened by its approach to ownership rather than being able to implement your own.

  • @alirezanet
    @alirezanet 9 месяцев назад +2

    You should claim rust is the best if you can compare it with something like Zig, I believe zig has the best of the two worlds

    • @pietraderdetective8953
      @pietraderdetective8953 5 месяцев назад +1

      Watch Primeagen videos..he often mentions Zig got 80% of Rust memory safety features, but is 80% easier to write compared to Rust.

  • @johnnm3207
    @johnnm3207 11 месяцев назад +4

    Zig >>>>>>>>>>

    • @AK-vx4dy
      @AK-vx4dy 11 месяцев назад +2

      What Zig ? It is amazing C replacement, but different beast :)

  • @KhaledKimboo4
    @KhaledKimboo4 5 месяцев назад +3

    what is ti with rust programmers i've never seen similar weird community of a programming language, i've used rust for 2 years along side C/python and Go recently, it is :
    a simple language + "best practices" enforced by the language
    anyone can by choice implement those concepts in any other language .
    for example
    all languages have mutex, rust enforces mutex wrappers on mutables to avoid lock-ins (you forget to unlock) the same wrapper could be implemented in any language in 10 lines of code only rust ENFORCES IT ON YOU and calls it a feature,
    get over yourself just learn the concepts and use any language you feel productive using (5% performance increase doesn't matter in 99.99% of your projects)
    by the way none of rust "best practices" are invented by rust team all are known techniques from 70's and 80's long before they were even born

  • @coolandonrs3680
    @coolandonrs3680 11 месяцев назад +2

    Now, I’m probably missing something, but why not just… share ownership? When an owner is removed from the stack, it or an intermediary just double checks there are no other owners before unallocating it. Yes, this requires storage to know the other owners, and possibly an intermediary process, but given you could using something like a hash table to store this minimal data compactly and quickly accessible, and the intermediary process (if it exists) would only be executed when needed, instead of constantly.
    Would this not minimally impact the efficiency of the concept, but remove all the drawbacks of switching ownership and multi-scoped variables? At least to me, this functionality concept of this seems to fundamentally break scope inherited variables in closures, which sounds terribly annoying.

    • @Mempler
      @Mempler 11 месяцев назад +1

      This would be referenced counting instead of ownership.
      Rust also has that with `Rc` but it does use a lot more memory and may even be really dangerous when doing multi threading when releasing both Rcs
      thats what Arc is for, a thread safe version of Rc with essentially a mutex to change the inner rc.
      correct me if i'm wrong.

    • @jacobpradels
      @jacobpradels  11 месяцев назад +2

      Great question! I really appreciate questions like this and I think it highlights something I forgot to mention in the video which is that one of the big benefits rust provides here is the ability to do this checking at compile time rather than runtime. And this allows for catching various kinds of bugs before code can even be built.
      The solution you mentioned sounds very similar to reference counting.
      I’m far from an expert in language design, but there are trade offs when you move in either direction.

    • @ianakotey
      @ianakotey 11 месяцев назад

      That exists in Rust too.

    • @coolandonrs3680
      @coolandonrs3680 11 месяцев назад

      Thanks for the informative answers!
      I’m not entirely sure why that wouldn’t be the default, but there probably is a good reason.
      I’ve been meaning to learn rust, if nothing else learning about this more might be a good reason to startx

    • @AK-vx4dy
      @AK-vx4dy 11 месяцев назад

      You can share immutable refenece easily in Rust, also you can "borrow" someting for a moment, all static at compile time.
      If you need runtime safe sharing there also many ways but the are explicit in Rust, explicit in function and additional cost.

  • @mohaofa1544
    @mohaofa1544 11 месяцев назад +5

    Rust Probaganda be like C is Old C++ is Bla bla bla and in the last minute they start talk about Rust and then the vedio end

  • @amuerta3041
    @amuerta3041 7 месяцев назад

    I don't really get the obsession with Rust's ownership model, yes its cool and almost always promises the programmer to handle memory deallocation in the end of the scope, but... combined complexity of other things in the language like enums that can hold values , Heap based types (Rc, Box,Arc,etc.) or Macros make it unbearable to quickly develop things. Problem that nearly everyone point at, of: "bug because of use after free" or "forgot to free() in C, unsafe!!!!" aren't as much of a deal as the unnecessary complexity of doing literally anything in the language.
    It could've be the case, if there where no debug tools, valrgrind or bounds checking in all of the system programming languages for decades. I doubt that you need majority of the features (even core one) in rust to make "safe software".

  • @strandingstranger
    @strandingstranger 6 месяцев назад +1

    you kinda sound like chris griffin

  • @rw_panic0_0
    @rw_panic0_0 11 месяцев назад +11

    someone pls explain to him Rust does not protect from memory leaks in the first place..

    • @peter9477
      @peter9477 6 месяцев назад +28

      It actually does. What you mean, I believe, is that it cannot prevent you from deliberately causing a leak (and obviously! given that it includes mem::leak()). But it definitely prevents inadvertent leaks in almost all cases by tracking ownership and dropping where required. That's what is meant, not that it's literally impossible to cause a leak.

    • @marcossidoruk8033
      @marcossidoruk8033 2 месяца назад +1

      ​@@peter9477 Reference cycles with reference counted pointers can produce memory leaks and many times its not trivial when those will happen.

    • @peter9477
      @peter9477 2 месяца назад

      @@marcossidoruk8033 How are you going to make those in Rust without using unsafe code?

  • @flurry301
    @flurry301 13 дней назад

    C better lol

  • @deadmarshal
    @deadmarshal 7 месяцев назад +3

    Rust is a joke!

    • @Simple_OG
      @Simple_OG 5 месяцев назад

      You are a joke

  • @MyWatermelonz
    @MyWatermelonz 3 месяца назад

    It is a big claim, going forward seems like python will be the best programming language

    • @epicmoofish3726
      @epicmoofish3726 3 месяца назад +1

      me waiting for my empty python for loop to finish (its on the 2nd iteration and its been 8 hours)

  • @erichstocker8358
    @erichstocker8358 26 дней назад

    No memory management isn't hard. Free the space. Why do you need some fascist language to enforce what decent programmers ought to be doing. Also, memory leaks may or may not be an issue in a program. It is inefficient and not good practice but depending upon the task it may or may not be an issue. Trading simplicity for complexity is not always the best solution.

  • @zxcaaq
    @zxcaaq 11 месяцев назад +3

    clickbait

  • @hahavx512
    @hahavx512 2 месяца назад

    Rust re-invents RAII. Wow. So cool. No.