Programming Articles - Page 1261 of 3363

Program arguments in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 13:21:14

134 Views

Taking care of arguments passed at the runtime is one of the key features of any programming language.In Rust, we access these arguments with the help of std::env::args, which returns an iterator that gives us a string for each passed argument.ExampleConsider the example shown below −use std::env; fn main() {    let args: Vec = env::args().collect();    // The first argument is the path that was used to call the program.    println!("My current directory path is {}.", args[0]);    println!("I got {:?} arguments: {:?}.", args.len() - 1, &args[1..]); }We can pass arguments like this −./args 1 2 3 4 ... Read More

Path Struct in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:40:28

456 Views

Path struct in Rust is used to represent the file paths in the underlying filesystem. It should also be noted that a Path in Rust is not represented as a UTF-8 string; instead, it is stored as a vector of bytes (Vec).ExampleConsider the example shown below − Live Demouse std::path::Path; fn main() {    // Create a `Path` from an `&'static str`    let path = Path::new(".");    // The `display` method returns a `Show`able structure    let display = path.display();    // Check if the path exists    if path.exists() {       println!("{} exists", display);    } ... Read More

Panic! Macro in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:38:40

332 Views

Handling critical errors in Rust is done with the help of panic! Macro. There are other ways to handle errors in Rust, but panic is unique in the sense that it is used to deal with unrecoverable errors.When we execute the panic! Macro, the whole program unwinds from the stack, and hence, it quits. Because of this manner with which the program quits, we commonly use panic! for unrecoverable errors.SyntaxThe syntax of calling a panic looks like this −panic!("An error was encountered");We usually pass a custom message inside the parentheses.ExampleConsider the code shown below as a reference − Live Demofn drink(beverage: ... Read More

Match in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:32:57

335 Views

Rust provides us with a match keyword that can be used for pattern matching. It is similar to the switch statement in C, and the first arm that matches is evaluated.ExampleConsider the example shown below −fn main() {    let number = 17;    println!("Tell me about {}", number);    match number {       1 => println!("One!")       2 | 3 | 5 | 7 | 11 => println!("A prime"),       13..=19 => println!("A teen"),       _ => println!("Ain't special"),    } }In the above example, we are trying to use a ... Read More

Loop Keyword in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:31:52

224 Views

Rust provides a loop keyword that allows us to run an infinite loop. The infinite loop indicated by the help of the loop keyword can be broken by the use of the break keyword. Also, we can exit an iteration and continue the infinite loop with the help of the continue keyword.ExampleConsider the example shown below − Live Demofn main() {    let mut count = 0u32;    println!("Infinite loop begins!!");    // Infinite loop    loop {       count += 1;       if count == 4 {          println!("four");         ... Read More

HashSet in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 13:04:16

627 Views

Rust also provides us with a HashSet data structure that is mainly used when we want to make sure that no duplicate values are present in our data structure.If we try to insert a new value into a HashSet that is already present in it, then the previous value gets overwritten by the new value that we insertedBesides the key features, a HashSet is also used to do the following operations −union − Extract all the unique elements in both sets.difference −G ets all the elements that are present in the first set, but not in the second.intersection − Gets ... Read More

HashMap in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:29:00

678 Views

HashMap is an important data structure, as it allows us to store data in key-value pairs. In Rust, HashMap stores values by key.HashMap keys can be Boolean, Integer, strings or any other data type that implements the Eq and Hash traits.HashMaps can grow in size, and when the space becomes too excessive, they can also shrink themselves.We can create a HashMap in multiple ways, we can use either HashMap::with_capacity(uint) or HashMap::new().Following are the methods that HashMaps support:insert()get()remove()iter()ExampleLet’s see an example where we build a HashMap and use all these operations stated above.Consider the example shown below. Live Demouse std::collections::HashMap; fn ... Read More

From and Into Traits In Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:28:03

354 Views

From and Into are two traits that Rust provides us. They are internally linked.From TraitWe make use of From trait when we want to define a trait to how to create itself from any other type. It provides a very simple mechanism with which we can convert between several types.For example, we can easily convert str into a String.ExampleConsider the example shown below: Live Demofn main() {    let my_str = "hello";    let my_string = String::from(my_str);    println!("{}", my_string); }OutputhelloWe can even convert our own types.ExampleConsider the example shown below:use std::convert::From; #[derive(Debug)] struct Num {    value: i64, } impl ... Read More

File Operations in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 12:50:15

341 Views

File operations normally include I/O operations. Rust provides us with different methods to handle all these operations.OpenRust provides an open static method that we can use to open a file in read-only mode.ExampleConsider the code shown below:use std::fs::File; use std::io::prelude::*; use std::path::Path; fn main() {    // Create a path to the desired file    let path = Path::new("out.txt");    let display = path.display();    let mut file = match File::open(&path) {       Err(why) => panic!("unable to open {}: {}", display, why),       Ok(file) => file,    };    let mut s = String::new();    match ... Read More

Enums in Rust Programing

Mukul Latiyan
Updated on 03-Apr-2021 14:25:50

214 Views

Also referred to as enumerations, enums are very useful in certain cases. In Rust, we use enums, as they allow us to define a type that may be one of a few different variants.Enumerations are declared with the keyword enum.Example Live Demo#![allow(unused)] #[derive(Debug)] enum Animal {    Dog,    Cat, } fn main() {    let mut b : Animal = Animal::Dog;    b = Animal::Cat;    println!("{:?}", b); }OutputCatZero-variant EnumsEnums in Rust can also have zero variants, hence the name Zero-variant enums. Since they do not have any valid values, they cannot be instantiated.Zero-variant enums are equivalent to the never ... Read More

Advertisements