Panic Macro in Rust Programming

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

307 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

311 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

203 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

HashMap in Rust Programming

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

632 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

331 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

Enums in Rust Programming

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

186 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

Constants in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:09:33

258 Views

Rust provides us with two types of constants. These are −const − an unchangeable valuestatic − possible mutable value with static lifetime.If we try to assign another value to an already declared const value, the compiler will throw an error.ExampleConsider the example shown below − Live Demostatic LANGUAGE: &str = "TutorialsPoint-Rust"; const THRESHOLD: i32 = 10; fn is_small(n: i32) -> bool {    n < THRESHOLD } fn main() {    // Error! Cannot modify a `const`.    THRESHOLD = 5;    println!("Everything worked fine!"); }In the above code, we are trying to modify the value of a variable that is ... Read More

Channels in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:06:35

759 Views

Channels are a medium that allow communication to take place between two or more threads. Rust provides asynchronous channels that enable communication between threads.Channels in Rust allow a unidirectional flow of communication between two endpoints. These two endpoints are Sender and Receiver.ExampleConsider the example shown below −use std::sync::mpsc::{Sender, Receiver}; use std::sync::mpsc; use std::thread; static NTHREADS: i32 = 3; fn main() {    let (tx, rx): (Sender, Receiver) = mpsc::channel();    let mut children = Vec::new();    for id in 0..NTHREADS {       let thread_tx = tx.clone();       let child = thread::spawn(move || {   ... Read More

Casting in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 14:05:17

406 Views

Casting or explicit conversion is only allowed in Rust, there’s no implicit conversion that the compiler of Rust does for us. It is known that, in many cases, implicit conversion can lead to data losses, which is not a good thing.Rules for converting between different types is pretty similar to C. In Rust though, we make use of as keyword when we want to convert from one type to another.Example:Consider the following example: Live Demo// Suppress all warnings from casts which overflow. #![allow(overflowing_literals)] fn main() {    let decimal = 65.43_f32;    // Error! No implicit conversion    // ... Read More

Arrays in Rust Programming

Mukul Latiyan
Updated on 03-Apr-2021 13:58:35

633 Views

An array is a data structure that is used to contain objects of the same type T. These objects are stored in contiguous memory locations.In Rust, the arrays are created by making the use of [ ] brackets. It is important that the size of the arrays must be known at the compile time. Also, unlike other languages like Java and C++, the length of the array is part of its type in Rust.[T; length].This means that an array of signature say, [i32, 4], is different from an array with the signature [i32, 5].Arrays can be immutable in nature and there ... Read More

Advertisements