I think SIMD actually uses dedicated vector types (from `std::simd`). a use case for u128 might be for large amounts of bit flags, or other cases where the number of bits is more relevant than the maximum number value
Some notes. 3:30 As someone said already, this is buggy. If pos is equal to the vector length, it will attempt to index out of bounds and panic. The standard library already has this kind of function that doesn't have bugs; the whole function body can be replaced with vector.get(pos) which returns an Option. It seems like you do know about this 5:22, I don't know why you didn't mention it. 4:56 This match statement really isn't any better than just calling .unwrap() on input_file. Both of them should display all of the same relevant information. You could also use .expect() to provide your own extra info along with the panic, but I don't think you have anything to add there, the error will already say what happened. 6:45 not stack variable, those are just regular variables declared with let. The correct one here is static variable, which are global variables. There are ways to have global mutable variables without unsafe, but global mutable variables are highly discouraged in general so don't do either unless you truly feel like you have to. 6:53 you say that not all unsafe code is bad, but actually this code _is_ bad as in it has undefined behavior. The rule that says when you have a mutable reference you cant have any other references applies to raw pointers as well, only the checker for it (that has few but existing false positives) is turned off and the optimizer will still make assumptions based on the rule. The only way to properly bypass this rule is using the UnsafeCell primitive type, which is what safe interior mutability types like RefCell and Mutex use internally.
> The rule that says when you have a mutable reference you cant have any other references applies to raw pointers as well This is somewhat unclear, but what it actually means is that the references *used to obtain the pointers* don't stop being relevant once you have pointers, because of pointer provenance (lmao) ... so if you first obtain a `\*mut` pointer from an `&mut`, then turn it into a `\*const` and then use both pointers at once - no UB (unless you create a data race or something). But if you create an `&` after your `&mut`, the `&mut` *and* the `\*mut` stop being valid, so using the original `\*mut` while the shared reference exists is UB, and also turning the `&` into an `\*mut` is also UB because the original reference isn't mutable. You may think this sounds ridiculous but I actually dealt with all of this when creating the `imgref-iter` crate so I'm quite familiar with pointer provenance lmao
1:47 - I would be hard pressed to call Rust macros just "syntactical sugar." Instead of being simple string replacements, they allow for arbitrary code execution at compile time, and their expansions are also subject to the same compiler checks as regular code. For example, you can write another programming language using Rust macros, and have the compiler give you errors for that language just as it would the surrounding Rust code.
A note on the _ keyword: using it as "let _ = ..." is redundary, as you can just call the expression as a standalone instruction. The only places where this is useful is when you want to silence the compiler warnings about an unused value, which commonly happen with arithmetic expressions and `Result`s. I wouldn't recommend making it a habit to use it, as you could end up accidentally ignoring `Result`s
I typically use it for functions I design to do a thing, but also return a thing for a different use case for the same function. The function does the same exact thing in both cases but one I don't care about the return value, like deleting from a list, sometimes I want the item deleted back but sometimes I don't care.
I also winced at the equivalence to C++ long. It’s a type alias that often refers to 64-bit ints, not 32. That’s one of the things that C++ allows that I don’t really like. Type aliases can be powerful, but they also obscure what your code is doing.
@@TheSast the "len < pos" will return false if len == pos. then the function would try to return Some(vector[vector.len()]), which will panic. Edit: just for non-rust programmers: there is a .get() method for vecs that does what the function in the video was supposed to do.
@@zero-gu3lt that’s what I use at work to tie third party libraries together for various things. It’s a headache working with different compiler implementations and build tools sometimes.
The highly underappreciated aspect of Rust is how, by virtue of how it's generally designed, with a very strong type system, algebraic data types, no NULL, having as many guarantees as possible, it's much easier to _make your invalid states unrepresentable._ In so many other languages that have NULL everywhere, you end up having to check it every time to make sure you don't run in something like a NullPointerException or a segfault; but in Rust, when you have a type T, it's *guaranteed* to be a T, you know it's not gonna be null. In so many other languages that don't have enums, you end up representing a superset of the state you need and you have to manually verify that it's valid; but in Rust, you can *always* just design your state in a way that it cannot possibly get into an invalid state in the first place. Now of course, C also has tagged unions, but the main problem with them is C itself. C doesn't have any kind of restrictive type system, pretty much nothing is guaranteed to be safe (not even the value of the enum in the tagged union), and most importantly, it doesn't even have type generics, which make the Rust's Result and Option types virtually impossible to represent in C unless you make a gazillion different types yourself. And other popular non-functional languages don't even have any kind of possibility to represent enums, so there's that.
Well that's technically true in Typescript too, it's just that most people don't learn to properly use the language and therefore never make use of its full range of type safety. IMO most of the issues with Typescript come from the fact that its best type-safety features are opt-in rather than enforced, unlike Rust, which makes the language overly appealing to amateurs with no clue of what they're doing. That's fundamentally why the Typescript ecosystem is so much worse than Rust's, it gives all the tools to succeed but is far too forgiving of shit practices.
@@boi8240 It means nothing if it's not enforced though. There should be a version of Typescript where it's enforced, then it would be a valid comparison
@@boi8240 does it apply to the hundreds of packages you could be using though? Or would it inform you that you'd have to make specific changes to these specific packages for it to be allowable in strict mode?
For me, the draw of rust was in two parts. The easy one was the error messages. When I first heard about rust, I was tooling around with Elm and someone compared it's (excellent) error messages with rusts. The one you didn't mention is concurrency. With it's Send and Sync traits plus Ownership, Rust actually allow you to give the compiler enough hints to be able to help prevent concurrent mutable access. My dream is that one day i'll be able to get the niceties of Erlang/OTP with the mechanical sympathy of C... Rust is, so far, as close as i've seen. 8:00 - Something that's interesting to note is that if you compile to a target that has access to SIMD ops, autovectorisation generally has an easier time making iterators work than hand coded loops. In this particular case, it looks like your for loop is simple enough that LLVM can pick it apart but i've seen cases where that wasn't so. (And, of course, can speculate about the opposite... compiler optimisations are both magical and fickle)
Well, there is a recent runtime called Lunatic that brings the BEAM actor model to anything that can compile to WASM, so rust too. They even did a web framework called Submillisecond in rust that uses all those features and implement a websocket too. It's really amazing and I think it will be a huge revolution in the backend ecosystem soon
Over the time you learn, that the compiler is helping you. Yes, it does give you a slap on the hand from time to time, but you usually quickly see why the way you tried to do things isn't the proper way
I like rust, but it seems not for the same reason most seem to, I'm not that fussed about the borrow checker, I just like how you can write clean concise code with it, much like python (while being more explicit and performant...). That said some crates I've come across seem to adopt quite messy APIs, C++ kinda has the same issue, it's not necessarily that clunky a language, it can be fairly brief, but sometimes it seems you don't have a choice because of the functions and objects you have to interface with. Still, early days for me, maybe I haven't found the right crates, maybe I don't understand them well enough, maybe their examples aren't the best, maybe crates that suit me better will come in the future, maybe I should just write them, maybe I should just use another language in specific use cases,. I quite like the idea of being able to do everything in rust (like until now I've been doing most things in python). And when I say do anything, I mean to be able to do it immediately, not have to sit there for ages figuring out how to get around it.
Agreed. I like that it is a performant clean language that is a true general purpose language. I've learned C/C++ in the past but getting off the ground with a real project is painful and slow and meticulous and god do I hate the linking dll's, and how you have to find a version of the dll that matches your planned compilation target, etc. Typical Rust development feels like a high level language with all the ergonomics and the dependency system is great, I can f12 in my IDE and see the source of my dependencies and you get all the benefits of a low level language and almost none of the cost. The only thing more difficult than high level languages is understanding the ownership system which become pretty easy once you've done it for a bit. It runs anywhere with minimal dev setup. I even installed the dev tools and rustup on my steam deck and do development on my steam deck when I'm on the go lol.
@@TheGeorey Mostly thinking about plotting in this instance, I don't like MATLAB as a general rule, but I like how easy you can plot, all you have to run is `plot(x, y)`, the similarly inspired matplotlib in python generates a quick line plot essentially the same. Now they are interpreted languages, so maybe this approach works better there, where to then add titles and legends and so on you can just slowly add the commands one after the other and iterate interactively/live. And to be fair, the plotly wrapper in rust is similarly simple, but it plots in a web browser and I would prefer a standalone window, the other plotting crates seem to be a little less simple. I was also keen to try dearimplot, but I seemed to struggle even just setting up a dearimgui gui more than in c++ where it seemed quite easy. For now it kinda looks like its best to do the compute in a rust lib with python bindings and do any visualisation there afterwards. Or maybe I can get used to plotly (but it is written in javascript).
To get more into many of the benefits of rust. I think you next should take a look at the type system (making own stuff). Enums, Structs, Impl, and Traits. those are some of the things I love the most in rust. Give you all the benefits of OOP and inheritens without the hassle, just a better developer experience imo.
if you started from some higher level language like js or python i would probably recommend trying c first. Rust is very nice, but it can get rather frustrating to learn.
@hanz1375 C is frustrating to write, I think being frustrated for some months or even years is much better than my whole career, I prefer writing JS my whole life over C, to that point!
@@b.wallet5295 depends on your field tbh. If you're a front end dev why the hell would you touch C/C++ or any low level languages lmao. Same is true if you're a systems engineer why tf would you even think about javascript
@@hanz1375 Although it seems to have successfully attracted a lot of developers who have moved to it straight from Python and similar. It doesn't hurt to have had at least some acquaintance with C first.
@@tourdesource You get a reference to the vec, aka a slice. In less abstract terms its just a pointer to the vec itself at pos 0 like you mentioned + the length. The only confusing bit is that for most types a reference would not be coerced into a slice, it would simply be a ptr to the typically stack allocated Vec, not to its underlying array. Ex: &String is a ptr to a String (which is a ptr to an underlying array, len, capacity) whereas &str type is directly a slice (ptr + length) to the underlying array of a String. Vec : ptr to elem[0], len, capacity. &Vec: ptr to elem[0], len.
And Microsoft, for showing their logo right in the first second of the video, despite Microsoft's trademark policy clearly stating "Don’t use Microsoft’s logos, icons, or designs, in any manner". We all can be sued for *everything*. Seeing this comment everywhere is getting really _really_ anoying.
@@peezieforestem5078 Is it? People with the goal to influence the situation have responded to proposed policy during the feedback period. I highly doubt that comments under random rust-related videos on TH-cam is the effective feedback channel to RSF.
>as a Java int, or a C++ long >C++ long The long data type in C and C++ is the most inconsistent data type, because it depends so much more frequently on platform. On Linux and MacOS, long is the size of a pointer. 32 bits on a 32-bit platform, 64 bits on a 64-bit platform. On Windows, it's always an i32.
but it hasn't all the restrictions on the memory model that make it possible, for the compiler, to reason about your code's values allocation behaviors and lifetimes
Learning Rust and tore out my hair over two things: (1) modules and namespaces (finally figured out each source file name is the module namespace that must be imported, with all variables within a modules being public within the module but not outside it, and, (2) impl functions for structures must accept some variation of &self or return the structure itself. you cannot have an impl fn accepting no parameters. The last problem is not well documented (all the noob examples don't mention it) and I was in a Panic! I was on the verge of doing the unthinkable: either quit learning Rust or ask StackOverflow for help!
Of course you can have functions that don't deal with `Self`! These are called associated functions and are used all over Rust. As an example look at `Box::leak` (and smart pointer functions in general, they can't use `self` because they dereference to the underlying type, which could lead to ambiguity).
@@marc8561 I said: "impl functions for structures must accept some variation of &self or return the structure itself. you cannot have an impl fn accepting no parameters." - I'm talking 'impl' functions, not general functions which of course can accept no parameters.
@@raylopez99 If I understand what you mean by "impl function", then these are called associated functions which again are used all over Rust. Maybe there's a miscommunication. `Box::leak` is an example of one such associated function (it's inside an `impl` block), not sure if you looked at it. Just search the std docs for it, I can't send a link because there's a 99.9% chance it will be flagged.
@@raylopez99 An associated function is invoked as `Example::bootoo()`. Of course you can't call it like a method as it's not a method. Associated functions and methods are different things.
I believe Microsoft will be leading the implementation of their core services in RUST. This might spark large adoption of software companies who has safety as a major parameter to go to RUST.
@@ThaiNguyen-gg8xj Do you know about the GCCRS project? The GCC team are working on a rust front end to the GCC compiler backend. That should make it better. Also LLVM already covers like 99.9% of use cases, C/C++ will still have a tiny niche but rust can definitely replace them outside of that niche.
Can you do a video on rust use cases (what you can do with rust) and also what you should actually use it for and not use it for. Cause I hear people say "Rust shouldn't be used for web dev (backend ofc) "
@@TheGeorey Alright. Thank you. Will check it out. I just get really confused when I see reddits that slam devs using rust for web (most of them end up leaning towards cli apps and more low level engineering)
@@olaniyanayodele5986 rust is amazing for CLIs for sure. Backend is still fairly good just not as mature as most frameworks, but far from terrible. There isn't a framework that handles full stack for you though afaik, maybe that's why people tend to discourage it
@@indiesigi7807 Where do I act like that? They hired those lawyers, just like Python Software Foundation hired theirs. I just say that instead of loosing my mind like it's some kind of hell on earth I looked at a trademark policy of another popular language and saw that this is normal in the industry. Is it good? No. Do I like it? No. I also don't like that google owns my soul according to ToS of youtube, but that's the world we live in. Haven't heard of anyone paying royalties to PSF for selling more than $1000 of python merch for example. They want 10% of your profits for your use of their trademark, but zero scandal about that. Doubt that someone at RSF or PSF would go after "the community", due to obvious bad optics, but the lawyers sure want to have an opportunity to sue (like its their job or something).
Having used both the C++ and Rust optinal the Rust optinal is better. While C++ does have optinal its not integrated into many apis. You also don't have the reference assignment issue in Rust. Without patern matching C++ can't "atomicly" give you access unless it's using the or_* operators which might not be what you want. One of the other nice Rust features is that size of &T is the same as size of optinal.
But the C++ optional is optional. And what about uninitialized pointers in an array or struct? Can't solve the null problem and maintain backwards compatibility.
It might be possible to write a lint like tool that checks for all unsafe null related behavior. It will create effectively a new language that is a subset of C++. But at that point just write a cross compiler and convert the code base to Rust.
1:15 "In order to make them mutable you just insert the 'mut' keyword" the way you pronounced it 😂😂😂 If ThePrimeagen got a hold of your video, you will be roasted to death🤣🤣🤣
Rust is great, but stay with it. There's only like 20 of us (haha) - there's not many though, but will be in time. It's definitely a great language, but it isn't for a beginner.
@@mennol3885 Rust was most influenced by the ML side of languages. Even the original compiler was made in OCaml, but the compiler has been written in rust itself for a very long time now.
I don't think this video discussed more complex ones and creating your own at all? You can look up "rust by example enums" to see a good example. Option and Result are just enums and not built in. You can make your own versions of them if you want. Also what do you mean less idiomatic? Of course by haskell standards haskell would be most idiomatic.
If there truly are problems in modern programming, why not switch back to old-school programming ? 🙂 I could hardly discuss Rust, but C++ for instance, is a programming language used to solving problems it had itself created 🙂
SoC vendors are already providing Rust toolchains. Linux kernel has Rust support. Safety critical software tools companies are demoing Rust tools on trade fairs. These things were traditionally the stronghold of C and C++. Now they are rewriting everything into Rust and at a very fast pace. If you think Rust is not going to replace C and C++ then you want to check again.
Because rust is much easier to learn than c++ and language checks everything for you from the box. So it's just easier to write code without bugs. Also, 10 lines of rust code in some driver that needs only 1/1000 Linux users does not mean that linux is rusted
Rust is 100% hype. Apart from Rust having a really klunky and awkward syntax, they have really poor error handling. Using return values to denote errors will result in your program having a really horrible control flow. Exceptions were invented for exactly this reason.
The exception is a goto to arbitrary point of the code without caller or callee knowing where it goes. How's that better? And you can call something "hype" all you want, but when established conservative codebases like linux and windows are integrating it and regular developers love it - what even is the meaning of "hype" at this point? Syntax is purely an opinion. You just get used to it, same as any other language, if it's worth it.
@@d3line "The exception is a goto" Not quite. The Exception is a structured flow of the program. It's very dissimilar from gotos. "without caller or callee knowing where it goes" That what makes Exceptions so great, that every caller does not have to take every possible error state into account. "You just get used to it, same as any other language, if it's worth it." Its probably not.
Exceptions just slow. A lot of modern c++ solutions are trying to write code without exceptions. Even there is a keyword "noexcept" - function wont throw, so compiler will optimize it.
@@niklas10101 Yeah, I understand that exception goes to the exception handler, not literally a random instruction. But it still breaks the observable control flow in the function. I want to know what my program does, so I don't use gotos, use conditions with early returns instead of nesting if's, refactor out functions, etc. But with exceptions I have to keep in mind that every function call is (from the control flow point of view) secretly an "if (succeeded) {...} else {...}" with "else" in another universe for all I know. It messes with the ability to understand code locally. C++ stack unwinding mechanism is accidentally Turing complete, you can't act as if it's simple to understand. For me, rust (and to the lesser degree, go) struck a different balance: there are still "panics", but they are never the control flow and always mean "programmer error, if compilers were smarter this would've been a compile time error". And in vast majority of cases they aren't handled by the user's code, since there's no meaningful way to recover, and just kill the program. In rust caller also doesn't have to take every possible error state into account: "let x = can_fail()?;" ≈ "if error {return error}". On the other hand, the caller has the option of dealing with all/some/none of the errors, which it doesn't with exceptions, because we don't know which exceptions even could be thrown at the call site. Java rightfully saw that as a problem. As for "is it worth it"... The computers are fast now, and the compute is cheap. It allows for k8s clusters of node apps that restart every hour as a fix for memory leaks in code. This annoys me. Most electron apps annoy me. I like correctness and efficiency, and rust gives me that, as well as near FP-level type system, witch I enjoy and miss in other languages (growls at go), and full leverage of the power of modern CPUs in all their many-cored glory.
@@denkalenichenko4124 Kind of an argument. But not really. Errors should be an exception (Pun). If your application needs to handle so many exceptions at a given moment that it impacts performance, then you should probably rethink your overall architectural decisions.
I do think you violated Rust trademark policy (probably they won't found out). Anyway, Rust is memory safe which is nice, but compile times are too slow for enjoying it even more
@@youarethecssformyhtml Well, because of safety I expect little bit slower compile times but Rust is too slow. 1) Huge codebases require big compile time and few saved minutes means a lot 2) Usage of 1 package requires compilation of 40+ packages which takes a lot of time to compile; compile time of Rust code without packages is reasonable, but with packages too big because 1 package equals to 40 packages
I would try out rust if it didn’t look so ugly. Whoever thought of copying the poorly executed method non typed languages used when they realized that types were actually pretty nice, needs their brain checked.
@@theroboman727 my man already got offended lmao. That's why I don't like it. The community. They are so toxic. They think they are superior just because they use the "safe" programming language.
FYI, Rust also has 128-bit size of integers. Usually, there's no need for such huge bits, unless doing something like SIMD operations.
didn’t know that, thanks!
@@SamirPatnaiki128 and u128
I think SIMD actually uses dedicated vector types (from `std::simd`).
a use case for u128 might be for large amounts of bit flags, or other cases where the number of bits is more relevant than the maximum number value
However, it lacks u256 which would be very cool in cryptographic applications... PS. I love Rust.
Some notes.
3:30 As someone said already, this is buggy. If pos is equal to the vector length, it will attempt to index out of bounds and panic. The standard library already has this kind of function that doesn't have bugs; the whole function body can be replaced with vector.get(pos) which returns an Option. It seems like you do know about this 5:22, I don't know why you didn't mention it.
4:56 This match statement really isn't any better than just calling .unwrap() on input_file. Both of them should display all of the same relevant information. You could also use .expect() to provide your own extra info along with the panic, but I don't think you have anything to add there, the error will already say what happened.
6:45 not stack variable, those are just regular variables declared with let. The correct one here is static variable, which are global variables. There are ways to have global mutable variables without unsafe, but global mutable variables are highly discouraged in general so don't do either unless you truly feel like you have to.
6:53 you say that not all unsafe code is bad, but actually this code _is_ bad as in it has undefined behavior. The rule that says when you have a mutable reference you cant have any other references applies to raw pointers as well, only the checker for it (that has few but existing false positives) is turned off and the optimizer will still make assumptions based on the rule. The only way to properly bypass this rule is using the UnsafeCell primitive type, which is what safe interior mutability types like RefCell and Mutex use internally.
> The rule that says when you have a mutable reference you cant have any other references applies to raw pointers as well
This is somewhat unclear, but what it actually means is that the references *used to obtain the pointers* don't stop being relevant once you have pointers, because of pointer provenance (lmao) ... so if you first obtain a `\*mut` pointer from an `&mut`, then turn it into a `\*const` and then use both pointers at once - no UB (unless you create a data race or something). But if you create an `&` after your `&mut`, the `&mut` *and* the `\*mut` stop being valid, so using the original `\*mut` while the shared reference exists is UB, and also turning the `&` into an `\*mut` is also UB because the original reference isn't mutable.
You may think this sounds ridiculous but I actually dealt with all of this when creating the `imgref-iter` crate so I'm quite familiar with pointer provenance lmao
3:48 feels like comparing Rust with the bad version of C++. There are obviously several ways to improve that C++ code and make it much safer.
1:47 - I would be hard pressed to call Rust macros just "syntactical sugar." Instead of being simple string replacements, they allow for arbitrary code execution at compile time, and their expansions are also subject to the same compiler checks as regular code. For example, you can write another programming language using Rust macros, and have the compiler give you errors for that language just as it would the surrounding Rust code.
macro_rules macros are just syntax sugar
A note on the _ keyword: using it as "let _ = ..." is redundary, as you can just call the expression as a standalone instruction. The only places where this is useful is when you want to silence the compiler warnings about an unused value, which commonly happen with arithmetic expressions and `Result`s. I wouldn't recommend making it a habit to use it, as you could end up accidentally ignoring `Result`s
It's useful for destructturing
The correct word is "redundant".
Be careful with "let _ = ..." because it has unusual (though documented) drop ordering.
I typically use it for functions I design to do a thing, but also return a thing for a different use case for the same function. The function does the same exact thing in both cases but one I don't care about the return value, like deleting from a list, sometimes I want the item deleted back but sometimes I don't care.
0:53 = C++: int32_t, not C++ long, they can be different on different machines
3:43 = The code is still buggy, what is index is equal to length
I also winced at the equivalence to C++ long. It’s a type alias that often refers to 64-bit ints, not 32. That’s one of the things that C++ allows that I don’t really like. Type aliases can be powerful, but they also obscure what your code is doing.
@@TheSast the "len < pos" will return false if len == pos. then the function would try to return Some(vector[vector.len()]), which will panic.
Edit: just for non-rust programmers: there is a .get() method for vecs that does what the function in the video was supposed to do.
@@TehKarmalizer try looking at Microsoft’s C++ 😂 sooo many aliases it looks like a different language
@@zero-gu3lt that’s what I use at work to tie third party libraries together for various things. It’s a headache working with different compiler implementations and build tools sometimes.
@@TheSast vector.len() < pos, does not evaluate to true for vector.len() == pos
The highly underappreciated aspect of Rust is how, by virtue of how it's generally designed, with a very strong type system, algebraic data types, no NULL, having as many guarantees as possible, it's much easier to _make your invalid states unrepresentable._
In so many other languages that have NULL everywhere, you end up having to check it every time to make sure you don't run in something like a NullPointerException or a segfault; but in Rust, when you have a type T, it's *guaranteed* to be a T, you know it's not gonna be null.
In so many other languages that don't have enums, you end up representing a superset of the state you need and you have to manually verify that it's valid; but in Rust, you can *always* just design your state in a way that it cannot possibly get into an invalid state in the first place.
Now of course, C also has tagged unions, but the main problem with them is C itself. C doesn't have any kind of restrictive type system, pretty much nothing is guaranteed to be safe (not even the value of the enum in the tagged union), and most importantly, it doesn't even have type generics, which make the Rust's Result and Option types virtually impossible to represent in C unless you make a gazillion different types yourself.
And other popular non-functional languages don't even have any kind of possibility to represent enums, so there's that.
Nice to see you here
Well that's technically true in Typescript too, it's just that most people don't learn to properly use the language and therefore never make use of its full range of type safety. IMO most of the issues with Typescript come from the fact that its best type-safety features are opt-in rather than enforced, unlike Rust, which makes the language overly appealing to amateurs with no clue of what they're doing. That's fundamentally why the Typescript ecosystem is so much worse than Rust's, it gives all the tools to succeed but is far too forgiving of shit practices.
@@boi8240 It means nothing if it's not enforced though. There should be a version of Typescript where it's enforced, then it would be a valid comparison
@@noahprussia7622 You can make it be enforced, that's what strict mode is, it's just that it's an opt-in feature.
@@boi8240 does it apply to the hundreds of packages you could be using though? Or would it inform you that you'd have to make specific changes to these specific packages for it to be allowable in strict mode?
For me, the draw of rust was in two parts. The easy one was the error messages. When I first heard about rust, I was tooling around with Elm and someone compared it's (excellent) error messages with rusts. The one you didn't mention is concurrency. With it's Send and Sync traits plus Ownership, Rust actually allow you to give the compiler enough hints to be able to help prevent concurrent mutable access. My dream is that one day i'll be able to get the niceties of Erlang/OTP with the mechanical sympathy of C... Rust is, so far, as close as i've seen.
8:00 - Something that's interesting to note is that if you compile to a target that has access to SIMD ops, autovectorisation generally has an easier time making iterators work than hand coded loops. In this particular case, it looks like your for loop is simple enough that LLVM can pick it apart but i've seen cases where that wasn't so. (And, of course, can speculate about the opposite... compiler optimisations are both magical and fickle)
Well, there is a recent runtime called Lunatic that brings the BEAM actor model to anything that can compile to WASM, so rust too. They even did a web framework called Submillisecond in rust that uses all those features and implement a websocket too. It's really amazing and I think it will be a huge revolution in the backend ecosystem soon
Over the time you learn, that the compiler is helping you. Yes, it does give you a slap on the hand from time to time, but you usually quickly see why the way you tried to do things isn't the proper way
I like rust, but it seems not for the same reason most seem to, I'm not that fussed about the borrow checker, I just like how you can write clean concise code with it, much like python (while being more explicit and performant...). That said some crates I've come across seem to adopt quite messy APIs, C++ kinda has the same issue, it's not necessarily that clunky a language, it can be fairly brief, but sometimes it seems you don't have a choice because of the functions and objects you have to interface with. Still, early days for me, maybe I haven't found the right crates, maybe I don't understand them well enough, maybe their examples aren't the best, maybe crates that suit me better will come in the future, maybe I should just write them, maybe I should just use another language in specific use cases,. I quite like the idea of being able to do everything in rust (like until now I've been doing most things in python). And when I say do anything, I mean to be able to do it immediately, not have to sit there for ages figuring out how to get around it.
Agreed. I like that it is a performant clean language that is a true general purpose language. I've learned C/C++ in the past but getting off the ground with a real project is painful and slow and meticulous and god do I hate the linking dll's, and how you have to find a version of the dll that matches your planned compilation target, etc.
Typical Rust development feels like a high level language with all the ergonomics and the dependency system is great, I can f12 in my IDE and see the source of my dependencies and you get all the benefits of a low level language and almost none of the cost. The only thing more difficult than high level languages is understanding the ownership system which become pretty easy once you've done it for a bit. It runs anywhere with minimal dev setup. I even installed the dev tools and rustup on my steam deck and do development on my steam deck when I'm on the go lol.
Yeah? Which crates are you referring to exactly?
@@TheGeorey Mostly thinking about plotting in this instance, I don't like MATLAB as a general rule, but I like how easy you can plot, all you have to run is `plot(x, y)`, the similarly inspired matplotlib in python generates a quick line plot essentially the same. Now they are interpreted languages, so maybe this approach works better there, where to then add titles and legends and so on you can just slowly add the commands one after the other and iterate interactively/live. And to be fair, the plotly wrapper in rust is similarly simple, but it plots in a web browser and I would prefer a standalone window, the other plotting crates seem to be a little less simple. I was also keen to try dearimplot, but I seemed to struggle even just setting up a dearimgui gui more than in c++ where it seemed quite easy. For now it kinda looks like its best to do the compute in a rust lib with python bindings and do any visualisation there afterwards. Or maybe I can get used to plotly (but it is written in javascript).
To get more into many of the benefits of rust. I think you next should take a look at the type system (making own stuff). Enums, Structs, Impl, and Traits. those are some of the things I love the most in rust. Give you all the benefits of OOP and inheritens without the hassle, just a better developer experience imo.
HOW DO YOU MAKE THESE KINDS OF ANIMATIONS?? Honestly would love a full tutorial on this topic
PowerPoint slides with transitions like morph
@@WaniTech nah i think there's a library like the 3b1b one for maths
Best quick Rust explaination for me ! Though short but explained deep enough ! Thanks !
I might start learning rust, I've been looking for a new language to start learning
if you started from some higher level language like js or python i would probably recommend trying c first. Rust is very nice, but it can get rather frustrating to learn.
@hanz1375 C is frustrating to write, I think being frustrated for some months or even years is much better than my whole career, I prefer writing JS my whole life over C, to that point!
@@b.wallet5295 depends on your field tbh. If you're a front end dev why the hell would you touch C/C++ or any low level languages lmao. Same is true if you're a systems engineer why tf would you even think about javascript
@@hanz1375 Although it seems to have successfully attracted a lot of developers who have moved to it straight from Python and similar. It doesn't hurt to have had at least some acquaintance with C first.
Rust supports also u128 and i128. You can also use 3rd party crates for a big integer, when no number of digits limitation.
Vector will not change it's address after reallocation. Elements inside vector will
Source?
In C++, &vec is identical to &vec[0]. Is that not the case in Rust? If so, why not?
@@tourdesource in rust &vec will return slice. Why? Rust doesn't do any fancy surprising conversions f.e. from vec to first element of a vector
@@tourdesource You get a reference to the vec, aka a slice. In less abstract terms its just a pointer to the vec itself at pos 0 like you mentioned + the length.
The only confusing bit is that for most types a reference would not be coerced into a slice, it would simply be a ptr to the typically stack allocated Vec, not to its underlying array. Ex: &String is a ptr to a String (which is a ptr to an underlying array, len, capacity) whereas &str type is directly a slice (ptr + length) to the underlying array of a String.
Vec : ptr to elem[0], len, capacity.
&Vec: ptr to elem[0], len.
You DESERVE a sub, the Pokemon battle with the borrow checker was amazing
Beware pal, you could get sued for using that Rust logo w/o clarifying you're not endorsed by the Foundation 🤣
We need an unicode character of the Rust logo. And use it everywhere.
Not yet
And Microsoft, for showing their logo right in the first second of the video, despite Microsoft's trademark policy clearly stating "Don’t use Microsoft’s logos, icons, or designs, in any manner". We all can be sued for *everything*. Seeing this comment everywhere is getting really _really_ anoying.
@@d3line Hey, that's a big part of why we post these comments.
@@peezieforestem5078 Is it? People with the goal to influence the situation have responded to proposed policy during the feedback period. I highly doubt that comments under random rust-related videos on TH-cam is the effective feedback channel to RSF.
Animations on this video are great. What did you use? Looks almost like manim? Maybe motion canvas? After effects?
1:16 - it's the mute keyword, not "mutt".
Finally, a rust video
The Rust movement with change everything from GPL to BSD and then companies will charge us for our own community efforts
>as a Java int, or a C++ long
>C++ long
The long data type in C and C++ is the most inconsistent data type, because it depends so much more frequently on platform. On Linux and MacOS, long is the size of a pointer. 32 bits on a 32-bit platform, 64 bits on a 64-bit platform. On Windows, it's always an i32.
the mutt keyword, which turns on dynamic typing, preventing you from telling the breed of your variables
3:43 where is the space after return type
😂
thanks i cant unsee that
Excellent overview.
well, c++ has Optional as well
but it hasn't all the restrictions on the memory model that make it possible, for the compiler, to reason about your code's values allocation behaviors and lifetimes
I would die to know the theme name, great content
rust is Zero Trust in code. Zero trust in the programmer, Zero trust in the caller of functions. Zero trust
Learning Rust and tore out my hair over two things: (1) modules and namespaces (finally figured out each source file name is the module namespace that must be imported, with all variables within a modules being public within the module but not outside it, and, (2) impl functions for structures must accept some variation of &self or return the structure itself. you cannot have an impl fn accepting no parameters.
The last problem is not well documented (all the noob examples don't mention it) and I was in a Panic! I was on the verge of doing the unthinkable: either quit learning Rust or ask StackOverflow for help!
Of course you can have functions that don't deal with `Self`! These are called associated functions and are used all over Rust. As an example look at `Box::leak` (and smart pointer functions in general, they can't use `self` because they dereference to the underlying type, which could lead to ambiguity).
@@marc8561 I said: "impl functions for structures must accept some variation of &self or return the structure itself. you cannot have an impl fn accepting no parameters." - I'm talking 'impl' functions, not general functions which of course can accept no parameters.
@@raylopez99 If I understand what you mean by "impl function", then these are called associated functions which again are used all over Rust. Maybe there's a miscommunication. `Box::leak` is an example of one such associated function (it's inside an `impl` block), not sure if you looked at it. Just search the std docs for it, I can't send a link because there's a 99.9% chance it will be flagged.
@@raylopez99 An associated function is invoked as `Example::bootoo()`. Of course you can't call it like a method as it's not a method. Associated functions and methods are different things.
@@marc8561 We agree then. thanks.
I believe Microsoft will be leading the implementation of their core services in RUST. This might spark large adoption of software companies who has safety as a major parameter to go to RUST.
Rust is not an acronym by the way, writing it in all caps is just awkward and nothing else.
As long as rust uses llvm, it cannot replace c/c++ 😢
@@ThaiNguyen-gg8xj can you elaborate please?
@@blankboy-ww7jt he clearly can't
@@ThaiNguyen-gg8xj Do you know about the GCCRS project? The GCC team are working on a rust front end to the GCC compiler backend. That should make it better.
Also LLVM already covers like 99.9% of use cases, C/C++ will still have a tiny niche but rust can definitely replace them outside of that niche.
More please! ❤❤❤
As someone not familiar with the rust syntax I understood jack shit
Can you do a video on rust use cases (what you can do with rust) and also what you should actually use it for and not use it for. Cause I hear people say "Rust shouldn't be used for web dev (backend ofc) "
Wym? Rust is amazing for backend. Highly recommend you this book "Zero to Production in Rust" if you're serious about it
@@TheGeorey Alright. Thank you. Will check it out. I just get really confused when I see reddits that slam devs using rust for web (most of them end up leaning towards cli apps and more low level engineering)
@@olaniyanayodele5986 rust is amazing for CLIs for sure. Backend is still fairly good just not as mature as most frameworks, but far from terrible. There isn't a framework that handles full stack for you though afaik, maybe that's why people tend to discourage it
@@sohn7767 Oh alright. Thank you
Be careful using the altered rust logo in thumbnail it could invite trademark infringement from the rust foundation.
😆
We should encourage everyone to use it everywhere, for Rust and non Rust related occasions.
1) it's a proposed policy
2) python has almost the same policy, it's just lawyers being lawyers and giving themselves tools
Does your comment is endorsed by R*** Foundation?
@@indiesigi7807 Where do I act like that? They hired those lawyers, just like Python Software Foundation hired theirs. I just say that instead of loosing my mind like it's some kind of hell on earth I looked at a trademark policy of another popular language and saw that this is normal in the industry. Is it good? No. Do I like it? No. I also don't like that google owns my soul according to ToS of youtube, but that's the world we live in.
Haven't heard of anyone paying royalties to PSF for selling more than $1000 of python merch for example. They want 10% of your profits for your use of their trademark, but zero scandal about that. Doubt that someone at RSF or PSF would go after "the community", due to obvious bad optics, but the lawyers sure want to have an opportunity to sue (like its their job or something).
6:17 you should probably use `println!` instead of `print!` here
Great job on this video!
Rust lawyers in here yet? I'm seeing their logo.
The trademark usage guidelines aren't finalized yet.
so this wasn't endorsed by the Rust Foundation, darnit
2:48 C++ has std::optional which works the same way
Rust-- has gone a long way, but it still can improve. For now Rust is the clear winner.
Having used both the C++ and Rust optinal the Rust optinal is better.
While C++ does have optinal its not integrated into many apis. You also don't have the reference assignment issue in Rust. Without patern matching C++ can't "atomicly" give you access unless it's using the or_* operators which might not be what you want. One of the other nice Rust features is that size of &T is the same as size of optinal.
But the C++ optional is optional. And what about uninitialized pointers in an array or struct?
Can't solve the null problem and maintain backwards compatibility.
It might be possible to write a lint like tool that checks for all unsafe null related behavior. It will create effectively a new language that is a subset of C++.
But at that point just write a cross compiler and convert the code base to Rust.
std::optional is optional.
std::optional is not as easy or concise to work with due to the lack of `match` syntax.
your content is Awesome
1:15
"In order to make them mutable you just insert the 'mut' keyword" the way you pronounced it 😂😂😂
If ThePrimeagen got a hold of your video, you will be roasted to death🤣🤣🤣
2:54 std::optional exists
Lifetimes?
mute not mutt
Rust is great, but stay with it. There's only like 20 of us (haha) - there's not many though, but will be in time. It's definitely a great language, but it isn't for a beginner.
This looks like a less idiomatic Haskell, very simple ADTs
For sure the Rust enums are borrowed from Haskell.
@@mennol3885 Rust was most influenced by the ML side of languages. Even the original compiler was made in OCaml, but the compiler has been written in rust itself for a very long time now.
I don't think this video discussed more complex ones and creating your own at all? You can look up "rust by example enums" to see a good example. Option and Result are just enums and not built in. You can make your own versions of them if you want.
Also what do you mean less idiomatic? Of course by haskell standards haskell would be most idiomatic.
if let else my friend
nice
mut is typically pronounced mute, not mutt
thank you
🦀🦀🦀
If there truly are problems in modern programming, why not switch back to old-school programming ? 🙂
I could hardly discuss Rust, but C++ for instance, is a programming language used to solving problems it had itself created 🙂
SoC vendors are already providing Rust toolchains. Linux kernel has Rust support. Safety critical software tools companies are demoing Rust tools on trade fairs. These things were traditionally the stronghold of C and C++. Now they are rewriting everything into Rust and at a very fast pace. If you think Rust is not going to replace C and C++ then you want to check again.
Yep Google reported less bugs and vulnerabilities in Android after rewriting some C++ libraries in Rust. 🦀 Is ❤
@@TheGeorey nah reject rust return to c/c++
@@Psi141 Ok boomer
@@AcidiFy574 im probably younger than you
Because rust is much easier to learn than c++ and language checks everything for you from the box. So it's just easier to write code without bugs.
Also, 10 lines of rust code in some driver that needs only 1/1000 Linux users does not mean that linux is rusted
Mut like mute not mutt
let muttable
Rust is 100% hype. Apart from Rust having a really klunky and awkward syntax, they have really poor error handling.
Using return values to denote errors will result in your program having a really horrible control flow. Exceptions were invented for exactly this reason.
The exception is a goto to arbitrary point of the code without caller or callee knowing where it goes. How's that better?
And you can call something "hype" all you want, but when established conservative codebases like linux and windows are integrating it and regular developers love it - what even is the meaning of "hype" at this point?
Syntax is purely an opinion. You just get used to it, same as any other language, if it's worth it.
@@d3line "The exception is a goto"
Not quite. The Exception is a structured flow of the program. It's very dissimilar from gotos.
"without caller or callee knowing where it goes"
That what makes Exceptions so great, that every caller does not have to take every possible error state into account.
"You just get used to it, same as any other language, if it's worth it."
Its probably not.
Exceptions just slow. A lot of modern c++ solutions are trying to write code without exceptions. Even there is a keyword "noexcept" - function wont throw, so compiler will optimize it.
@@niklas10101 Yeah, I understand that exception goes to the exception handler, not literally a random instruction. But it still breaks the observable control flow in the function. I want to know what my program does, so I don't use gotos, use conditions with early returns instead of nesting if's, refactor out functions, etc.
But with exceptions I have to keep in mind that every function call is (from the control flow point of view) secretly an "if (succeeded) {...} else {...}" with "else" in another universe for all I know. It messes with the ability to understand code locally. C++ stack unwinding mechanism is accidentally Turing complete, you can't act as if it's simple to understand.
For me, rust (and to the lesser degree, go) struck a different balance: there are still "panics", but they are never the control flow and always mean "programmer error, if compilers were smarter this would've been a compile time error". And in vast majority of cases they aren't handled by the user's code, since there's no meaningful way to recover, and just kill the program.
In rust caller also doesn't have to take every possible error state into account: "let x = can_fail()?;" ≈ "if error {return error}". On the other hand, the caller has the option of dealing with all/some/none of the errors, which it doesn't with exceptions, because we don't know which exceptions even could be thrown at the call site. Java rightfully saw that as a problem.
As for "is it worth it"... The computers are fast now, and the compute is cheap. It allows for k8s clusters of node apps that restart every hour as a fix for memory leaks in code. This annoys me. Most electron apps annoy me. I like correctness and efficiency, and rust gives me that, as well as near FP-level type system, witch I enjoy and miss in other languages (growls at go), and full leverage of the power of modern CPUs in all their many-cored glory.
@@denkalenichenko4124 Kind of an argument. But not really.
Errors should be an exception (Pun).
If your application needs to handle so many exceptions at a given moment that it impacts performance, then you should probably rethink your overall architectural decisions.
I do think you violated Rust trademark policy (probably they won't found out).
Anyway, Rust is memory safe which is nice, but compile times are too slow for enjoying it even more
Slow compile times are to make sure your code is safe and performant in runtime
@@youarethecssformyhtml Well, because of safety I expect little bit slower compile times but Rust is too slow.
1) Huge codebases require big compile time and few saved minutes means a lot
2) Usage of 1 package requires compilation of 40+ packages which takes a lot of time to compile; compile time of Rust code without packages is reasonable, but with packages too big because 1 package equals to 40 packages
Slow compile time is its biggest weakness but it is being worked on. I've no idea how much better they will be able to make it though.
@@kevinmcfarlane2752 someone has to pay for abstractions. There's always a trade-off
your voice is so low
no crablang for the win
Muttttttt
I would try out rust if it didn’t look so ugly. Whoever thought of copying the poorly executed method non typed languages used when they realized that types were actually pretty nice, needs their brain checked.
i dont like rust
Everyone had to know...
Thats fine. I like it
Alright, would be cool if you elaborated on why though.
@@theroboman727 my man already got offended lmao. That's why I don't like it. The community. They are so toxic. They think they are superior just because they use the "safe" programming language.
@@Psi141 or maybe they're highly excited, what's toxic in it?