5 Better ways to code in Rust

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up our stations in this video I'll show you five ways to improve your coding experience in Rust whether you're a complete beginner or an experienced thrust developer these tips will be valuable to you at the end of the video I'll also give you a sixth bonus tip that's pretty controversial so make sure to stick around for that alright let's get started assuming you already have rust installed the next thing you want to do is make sure you properly set up your IDE vs code is my go-to choice because it's easy to use available on all major operating systems and is highly configurable to configure vs code for rust development there are three must-have extensions and a few optional yet very powerful extensions I highly recommend here are the three must-have extensions first we have rust analyzer which is rust's official language server providing features like code completion go to definition inlay hints and more next is code lldb this extension will allow you to debug your rust code next is better tommo which provides syntax highlighting for toml files with these three extensions you're all set up for rust development there are also a few very powerful optional extensions I highly recommend aerolens will improve the highlighting of errors and warnings as you can see in this example it will make errors stand out more and display the error message in line next is to do tree which will help you quickly find to do items in your code one cool thing about to do tree is that it matches to do items by using a regular expression which you can change in this example I've changed the regular expression so that it also highlights the to do macro so when I'm writing rust code my to do comments and to do macros get highlighted lastly we have the crates extension which allows you to easily check if your dependencies are out of date inside your cargo.tomo file if a dependency is out of date you'll see a red X followed by the latest version of that dependency next let's talk about setting up your rust project specifically we'll cover how to configure automatic linting and formatting take advantage of live reloading and set up continuous integration when you install the rust tool chain it comes with two very useful tools clippy and rust format clippy is a configurable linter that catches common mistakes and improves your rust code and rust format is a configurable tool for formatting rust code according to Style Guidelines now you could use these tools by running them manually in your terminal however I like to configure them to run automatically let's see how you could do that in vs code to configure clippy to run automatically open up settings in vs code and in the search bar type in Rust Dash analyzer space check then scroll down until you see the check command and then change check to Clippy now if we open up main.rs you can see that we get a warning because we're using a variable name that clippy does not allow to configure rust format to run automatically we'll go back to settings and switch over to the Json file configuration then all you need is these two configurations make sure the default formatter is rust analyzer and format on Save is set to true then if we go back to main.rs and change the code formatting it will be fixed when we save the file next let's talk about how to set up live reloading using cargo watch cargo watch is a cargo plugin that watches for changes in your project source files and runs cargo commands when they occur to install cargo watch run cargo add cargo watch then you can run cargo watch this is the specific command I like to run Dash Q stands for quiet and it will suppress the output of cargo watch Dash c will clear the screen Dash W allows us to specify which files and folders to watch in this case only the source directory will be watched and dash X allows us to specify which cargo command to execute in this case we're executing cargo run with the Q option which will prevent cargo log messages from being printed if we execute this command our program will be ran then if we change the code it will be recompiled lastly let's talk about setting up continuous integration with GitHub actions to set up a continuous integration for our project all we need to do is create a DOT GitHub folder which contains a workflows folder which in turn contains yaml files defining our workflows here's an example of a simple workflow called rust CI it runs anytime code changes are pushed to the main branch or anytime a pull request us targets the main branch this workflow has one job with a few steps first our code is checked out then we install cargo audit which will allow us to audit our code base for vulnerabilities then the code is built and tested then we run cargo clippy and fail the build if any warnings appear and finally we run cargo audit if our project dependencies contain any known vulnerabilities then the build will fail with automatic linting and formatting live reloading and continuous integration our project is now properly set up and we're ready to start coding the next tip has to do with how you should approach writing your Russ programs over engineering is a common problem in software development and occurs when you code something that's more complex or elaborate than it needs to be this is something you definitely want to avoid when riding rust instead you should follow the principle of make it work then make it right and then make it fast first write code that simply solves the problem or accomplish pushes the goal it doesn't matter if it's not the most idiomatic or performant code then once your code is working you can make it more idiomatic and finally performant let's take a look at an example here we have a function called calculate sum which takes an array of integers and Returns the sum the code works but it's not the most idiomatic rust code for example inside the calculate sum function we're using a for Loop instead of an iterator adapter method and inside the main function we're using unwrap on the result type returned from calculate sum instead of handling the error case now that the code is working we can make it more idiomatic by fixing these issues inside calculate sum we're now using the sum method instead of a for Loop and inside the main function we're matching on the result type returned from calculate sum the code is now idiomatic next we can think about performance to squeeze out more performance we'll introduce parallelism using the rayon crate all we have to do is include the rayon Prelude and in instead of calling itter inside calculate sum we call Par iter which stands for parallel iterator rayon will do the hard work of figuring out how to parallelize our program this is why rayon is a useful and very popular rust crate speaking of rust crates the next tip is to get yourself familiar with some of the most popular third-party crates this is especially important because rust is known to have a small standard Library so when you're coding up any meaningful project you'll start reaching for third-party dependencies pretty soon key crates you should know include surday and certain Json which are used to serialize and deserialize your data types two other important crates are this error and anyhow which are both used for error handling Tokyo is another crate you should know it's the most popular async runtime for rust there are plenty of other important crates which I don't have time to go over in this video but if you want a curated list of rust crates blessed RS is a great resource now that you know how to approach coding in Rust and which third-party crates you should know the next tip is to learn rust specific design patterns for example the extension tray pattern which allows you to add methods to a type outside of the crate where the type was defined extension traits are particularly common when you want to extend the functionality of types in the standard Library let's take a look at an example inside a crate imagine we Define a public trait called palindrome with one function is palindrome that returns a Boolean then we implement the palindrome tray for the string type in the standard Library we can then import this trait in another crate and all the string types will have access to the is palindrome method as you can see this pattern allows us to easily extend the functionality of types in the standard Library some other design patterns that you should be aware of are the type stay pattern interior immunability raii and and the Builder pattern let me know in the comment section below if you want me to make a video going through these specific patterns now let's move on to the controversial bonus tip but before we get to that make sure you get your free rust cheat sheet by heading over to let's get rusty.com cheat sheet the sixth bonus tip is to leverage AI now there's a lot of excitement and fear around AI but no matter what you think it's here to stay so might as well get familiar with it and take advantage personally I think AI is an amazing tool that can make you a lot more productive for example tools like GitHub copilot can help you write more idiomatic rust code or help you quickly Implement code that's repetitive or generic Chad GPT is also a really useful tool in fact it wrote the GitHub actions workflow file from earlier in this video so again make sure to get educated and take advantage of these tools that's it for this video before you go make sure to get your free rust cheat sheet at let's get rusty.com cheat sheet give this video a like if you enjoyed it and subscribe to the channel for weekly rust content with that said I'll see you in the next one
Info
Channel: Let's Get Rusty
Views: 106,317
Rating: undefined out of 5
Keywords: RustProgramming, CodingInRust, RustTutorials, AdvancedRustTechniques, RustOwnershipSystem, PatternMatchingInRust, OptimizingPerformanceInRust, RustTipsAndTricks, RustCodingSkills, CleanCodeInRust, efficientrustprogramming, RustDevelopment, RustBestPractices, RustCodeOptimization, RustCodeExamples, ProgrammingLanguages, letsgetrusty, rust2023, rusttutorials, rustforbeginners, rustprogramming, rustlanguange, rustlanguange2023, codebetterinrust, rusttipsandtricks, rustcodingtechniques, cleancodeinrust
Id: BU1LYFkpJuk
Channel Id: undefined
Length: 9min 51sec (591 seconds)
Published: Sat May 27 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.