
[ad_1]
Rust Beginner Tips
This time I want to bring to you a very simple post with six very basic tips and recommendations for people just starting out with Rust.
you probably coded something match
With a single matching branch and an empty block to do nothing with the rest of the options. take an action only when you receive Some(foo)
, Err(error)
either Ok(bar)
, For example. For those cases we have if let
,
It comes with personal preferences but it can be really useful in cases when you keep declaring the same result over and over again in the same file or module. It is even used in std
library as you can see std::io::Result
,

These two macros can be really useful for some projects, especially when building prototypes based on text input or creating small programs with challenges such as advent of the code,
Their use is very simple, they read a file in the specified path and save the contents to a constant when the file is initialized. This won’t let you hard-code some problematic or large string constants, which you can also remove with version control.
If you come from other languages and you want to iterate a collection and get the index at the same time you will probably default to code in a for loop iterating numbers between zero and the length of the collection and Can then access the items in the index. In Rust you can use Counting of,
enumerate
is one of the terrible ways iterator attribute, Adding this method at the end of an iterator invocation will convert the contents of each loop into a tuple containing the index and value of the item.
Self is a powerful keyword that can have an entire post of its own, especially when you use it. Defining CharacteristicsBut its most basic use is a good recommendation when you implement structs.
This will allow you to refer to the block owner with a certain term, for example, it can save you some time if you decide to rename the structure.
Many times we have to implement functions that read a collection of elements. In those cases we can request &[T]
instead of borrow vector. This will provide us with similar functionality (if we do read only intent) Too much flexibility.
And that’s all for today. In the future, it is possible that I make a second version with some additional little tips such as the use of blocks or some useful macros. Until then, you can take a look example repository as always.
[ad_2]
Source link
#Recommendations #Improving #Rust #Code #SotoEstevez