How rust forces you to respect memory

  Рет қаралды 7,110

Jacob Pradels

Jacob Pradels

8 ай бұрын

(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.

Пікірлер: 52
@DuskyDaily
@DuskyDaily 8 ай бұрын
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.
@danilfun
@danilfun 8 ай бұрын
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 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 2 ай бұрын
@@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 2 күн бұрын
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.
@pitbul2877
@pitbul2877 8 ай бұрын
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 8 ай бұрын
Is it not a safe pattern to keep using though? Just in case, you know
@pitbul2877
@pitbul2877 8 ай бұрын
@@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 3 ай бұрын
I C it's ok, but in C++ casting is needed@@scrambledmandible
@hcn6708
@hcn6708 28 күн бұрын
"Ok, so hear me out on this: Rust" _mixed reaction from the crowd_
@pshr2447
@pshr2447 8 ай бұрын
Great video btw actually made me so curious that i would like to learn more about rust
@alvaroluis5368
@alvaroluis5368 8 ай бұрын
This concept is called RAII and you could do it in C++ years before Rust existed
@pshr2447
@pshr2447 8 ай бұрын
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 8 ай бұрын
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 2 ай бұрын
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 Сағат бұрын
@@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.
@CliveStewart-bq3od
@CliveStewart-bq3od 2 ай бұрын
Very clear and understanding .. you must do more videos like this
@whereispie
@whereispie 21 күн бұрын
Awesome, thanks
@ErikBongers
@ErikBongers 4 ай бұрын
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 8 ай бұрын
Thank you for the great video!! what software do you use to make such illustrations?
@tru2thastyle
@tru2thastyle Күн бұрын
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.
@darrellplank4518
@darrellplank4518 7 ай бұрын
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.
@SamualN
@SamualN Ай бұрын
how does this apply when using async though?
@MikeDawson1
@MikeDawson1 8 ай бұрын
isn't this just like an std::vector though?
@KhaledKimboo4
@KhaledKimboo4 Ай бұрын
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
@mohaofa1544
@mohaofa1544 7 ай бұрын
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
@strandingstranger
@strandingstranger 2 ай бұрын
you kinda sound like chris griffin
@zeropointer125
@zeropointer125 8 ай бұрын
Wait... but c++ does pretty much the same things. Only difference is = copies by default and you have to explicitly std::move
@coolandonrs3680
@coolandonrs3680 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
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 8 ай бұрын
That exists in Rust too.
@coolandonrs3680
@coolandonrs3680 8 ай бұрын
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 8 ай бұрын
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.
8 ай бұрын
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.
@maelstrom254
@maelstrom254 8 ай бұрын
C++ works exactly as described in the video 😂
@ifgpuelse
@ifgpuelse 8 ай бұрын
C++ Smart pointers: I don't exist**
@rw_panic0_0
@rw_panic0_0 7 ай бұрын
someone pls explain to him Rust does not protect from memory leaks in the first place..
@peter9477
@peter9477 2 ай бұрын
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.
@alirezanet
@alirezanet 6 ай бұрын
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 2 ай бұрын
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 8 ай бұрын
Zig >>>>>>>>>>
@AK-vx4dy
@AK-vx4dy 8 ай бұрын
What Zig ? It is amazing C replacement, but different beast :)
@amuerta3041
@amuerta3041 3 ай бұрын
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".
@MyWatermelonz
@MyWatermelonz 2 күн бұрын
It is a big claim, going forward seems like python will be the best programming language
@deadmarshal
@deadmarshal 3 ай бұрын
Rust is a joke!
@Simple_OG
@Simple_OG Ай бұрын
You are a joke
@zxcaaq
@zxcaaq 8 ай бұрын
clickbait
The Secret to Rust Ownership: Rc vs. Arc
13:47
Flo Woelki
Рет қаралды 1,6 М.
Зачем системным программистам Rust? Сергей Фомин, Яндекс
44:37
Видео с мероприятий {speach!
Рет қаралды 7 М.
МАМА И STANDOFF 2 😳 !FAKE GUN! #shorts
00:34
INNA SERG
Рет қаралды 4,3 МЛН
Please be kind🙏
00:34
ISSEI / いっせい
Рет қаралды 192 МЛН
ОСКАР ИСПОРТИЛ ДЖОНИ ЖИЗНЬ 😢 @lenta_com
01:01
WHO DO I LOVE MOST?
00:22
dednahype
Рет қаралды 79 МЛН
Understanding Ownership in Rust
25:31
Let's Get Rusty
Рет қаралды 243 М.
Arc instead of Vec? | Prime Reacts
37:18
ThePrimeTime
Рет қаралды 62 М.
Rust makes you feel like a GENIUS
10:48
No Boilerplate
Рет қаралды 401 М.
8 deadly mistakes beginner Rust developers make
14:14
Let's Get Rusty
Рет қаралды 158 М.
Visualizing memory layout of Rust's data types
39:39
Sreekanth
Рет қаралды 10 М.
You Are WRONG About 0 Based Indexing
25:02
ThePrimeTime
Рет қаралды 247 М.
No really, how does Linux run executables?
8:37
Jacob Pradels
Рет қаралды 178 М.
Learning Rust: Memory, Ownership and Borrowing
7:46
YouCodeThings
Рет қаралды 89 М.
This Algorithm is 1,606,240% FASTER
13:31
ThePrimeagen
Рет қаралды 754 М.
Rust Data Modelling Without Classes
11:25
No Boilerplate
Рет қаралды 164 М.
Что не так с яблоком Apple? #apple #macbook
0:38
Не шарю!
Рет қаралды 429 М.
Как слушать музыку с помощью чека?
0:36
После ввода кода - протирайте панель
0:18
Up Your Brains
Рет қаралды 1 МЛН
Main filter..
0:15
CikoYt
Рет қаралды 14 МЛН
Спутниковый телефон #обзор #товары
0:35
Product show
Рет қаралды 1,9 МЛН
Урна с айфонами!
0:30
По ту сторону Гугла
Рет қаралды 8 МЛН