Rust – Loop

Rust – Loop ”; Previous Next There may be instances, where a block of code needs to be executed repeatedly. In general, programming instructions are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. Given below is the general form of a loop statement in most of the programming languages. Rust provides different types of loops to handle looping requirements − while loop for Definite Loop A loop the number of iterations of which is definite/fixed is termed as a definite loop. The for loop is an implementation of a definite loop. For Loop The for loop executes the code block for a specified number of times. It can be used to iterate over a fixed set of values, such as an array. The syntax of the for loop is as given below Syntax for temp_variable in lower_bound..upper_bound { //statements } An example of a for loop is as shown below fn main(){ for x in 1..11{ // 11 is not inclusive if x==5 { continue; } println!(“x is {}”,x); } } NOTE: that the variable x is only accessible within the for block. Output x is 1 x is 2 x is 3 x is 4 x is 6 x is 7 x is 8 x is 9 x is 10 Indefinite Loop An indefinite loop is used when the number of iterations in a loop is indeterminate or unknown. Indefinite loops can be implemented using − Sr.No Name & Description 1 While The while loop executes the instructions each time the condition specified evaluates to true 2 Loop The loop is a while(true) indefinite loop Illustration − for while fn main(){ let mut x = 0; while x < 10{ x+=1; println!(“inside loop x value is {}”,x); } println!(“outside loop x value is {}”,x); } The output is as shown below − inside loop x value is 1 inside loop x value is 2 inside loop x value is 3 inside loop x value is 4 inside loop x value is 5 inside loop x value is 6 inside loop x value is 7 inside loop x value is 8 inside loop x value is 9 inside loop x value is 10 outside loop x value is 10 Illustration −loop fn main(){ //while true let mut x = 0; loop { x+=1; println!(“x={}”,x); if x==15 { break; } } } The break statement is used to take the control out of a construct. Using break in a loop causes the program to exit the loop. Output x=1 x=2 x=3 x=4 x=5 x=6 x=7 x=8 x=9 x=10 x=11 x=12 x=13 x=14 x=15 Continue Statement The continue statement skips the subsequent statements in the current iteration and takes the control back to the beginning of the loop. Unlike the break statement, the continue does not exit the loop. It terminates the current iteration and starts the subsequent iteration. An example of the continue statement is given below. fn main() { let mut count = 0; for num in 0..21 { if num % 2==0 { continue; } count+=1; } println! (” The count of odd values between 0 and 20 is: {} “,count); //outputs 10 } The above example displays the number of even values between 0 and 20. The loop exits the current iteration if the number is even. This is achieved using the continue statement. The count of odd values between 0 and 20 is 10 Print Page Previous Next Advertisements ”;

Rust – String

Rust – String ”; Previous Next The String data type in Rust can be classified into the following − String Literal(&str) String Object(String) String Literal String literals (&str) are used when the value of a string is known at compile time. String literals are a set of characters, which are hardcoded into a variable. For example, let company=”Tutorials Point”. String literals are found in module std::str. String literals are also known as string slices. The following example declares two string literals − company and location. fn main() { let company:&str=”TutorialsPoint”; let location:&str = “Hyderabad”; println!(“company is : {} location :{}”,company,location); } String literals are static by default. This means that string literals are guaranteed to be valid for the duration of the entire program. We can also explicitly specify the variable as static as shown below − fn main() { let company:&”static str = “TutorialsPoint”; let location:&”static str = “Hyderabad”; println!(“company is : {} location :{}”,company,location); } The above program will generate the following output − company is : TutorialsPoint location :Hyderabad String Object The String object type is provided in Standard Library. Unlike string literal, the string object type is not a part of the core language. It is defined as public structure in standard library pub struct String. String is a growable collection. It is mutable and UTF-8 encoded type. The String object type can be used to represent string values that are provided at runtime. String object is allocated in the heap. Syntax To create a String object, we can use any of the following syntax − String::new() The above syntax creates an empty string String::from() This creates a string with some default value passed as parameter to the from() method. The following example illustrates the use of a String object. fn main(){ let empty_string = String::new(); println!(“length is {}”,empty_string.len()); let content_string = String::from(“TutorialsPoint”); println!(“length is {}”,content_string.len()); } The above example creates two strings − an empty string object using the new method and a string object from string literal using the from method. The output is as shown below − length is 0 length is 14 Common Methods – String Object Sr.No. Method Signature Description 1 new() pub const fn new() → String Creates a new empty String. 2 to_string() fn to_string(&self) → String Converts the given value to a String. 3 replace() pub fn replace<”a, P>(&”a self, from: P, to: &str) → String Replaces all matches of a pattern with another string. 4 as_str() pub fn as_str(&self) → &str Extracts a string slice containing the entire string. 5 push() pub fn push(&mut self, ch: char) Appends the given char to the end of this String. 6 push_str() pub fn push_str(&mut self, string: &str) Appends a given string slice onto the end of this String. 7 len() pub fn len(&self) → usize Returns the length of this String, in bytes. 8 trim() pub fn trim(&self) → &str Returns a string slice with leading and trailing whitespace removed. 9 split_whitespace() pub fn split_whitespace(&self) → SplitWhitespace Splits a string slice by whitespace and returns an iterator. 10 split() pub fn split<”a, P>(&”a self, pat: P) → Split<”a, P> , where P is pattern can be &str, char, or a closure that determines the split. Returns an iterator over substrings of this string slice, separated by characters matched by a pattern. 11 chars() pub fn chars(&self) → Chars Returns an iterator over the chars of a string slice. Illustration: new() An empty string object is created using the new() method and its value is set to hello. fn main(){ let mut z = String::new(); z.push_str(“hello”); println!(“{}”,z); } Output The above program generates the following output − hello Illustration: to_string() To access all methods of String object, convert a string literal to object type using the to_string() function. fn main(){ let name1 = “Hello TutorialsPoint , Hello!”.to_string(); println!(“{}”,name1); } Output The above program generates the following output − Hello TutorialsPoint , Hello! Illustration: replace() The replace() function takes two parameters − the first parameter is a string pattern to search for and the second parameter is the new value to be replaced. In the above example, Hello appears two times in the name1 string. The replace function replaces all occurrences of the string Hello with Howdy. fn main(){ let name1 = “Hello TutorialsPoint , Hello!”.to_string(); //String object let name2 = name1.replace(“Hello”,”Howdy”); //find and replace println!(“{}”,name2); } Output The above program generates the following output − Howdy TutorialsPoint , Howdy! Illustration: as_str() The as_str() function extracts a string slice containing the entire string. fn main() { let example_string = String::from(“example_string”); print_literal(example_string.as_str()); } fn print_literal(data:&str ){ println!(“displaying string literal {}”,data); } Output The above program generates the following output − displaying string literal example_string Illustration: push() The push() function appends the given char to the end of this String. fn main(){ let mut company = “Tutorial”.to_string(); company.push(”s”); println!(“{}”,company); } Output The above program generates the following output − Tutorials Illustration: push_str() The push_str() function appends a given string slice onto the end of a String. fn main(){ let mut company = “Tutorials”.to_string(); company.push_str(” Point”); println!(“{}”,company); } Output The above program generates the following output − Tutorials Point Illustration: len() The len() function returns the total number of characters in a string (including spaces). fn main() { let fullname = ” Tutorials Point”; println!(“length is {}”,fullname.len()); } Output The above program generates the following output − length is 20 Illustration: trim() The trim() function removes leading and trailing spaces in a string. NOTE that this function will not remove the inline spaces. fn main() { let fullname = ” Tutorials Point rn”; println!(“Before trim “); println!(“length is {}”,fullname.len()); println!(); println!(“After trim “); println!(“length is {}”,fullname.trim().len()); } Output The above program generates the following output − Before trim length is 24 After trim length is 15 Illustration:split_whitespace() The split_whitespace() splits the input string into different strings. It returns an iterator so we are iterating through the tokens as shown below − fn main(){ let msg = “Tutorials Point has good

Rust – Package Manager

Rust – Package Manager ”; Previous Next Cargo is the package manager for RUST. This acts like a tool and manages Rust projects. Some commonly used cargo commands are listed in the table below − Sr.No Command & Description 1 cargo build Compiles the current project. 2 cargo check Analyzes the current project and report errors, but don”t build object files. 3 cargo run Builds and executes src/main.rs. 4 cargo clean Removes the target directory. 5 cargo update Updates dependencies listed in Cargo.lock. 6 cargo new Creates a new cargo project. Cargo helps to download third party libraries. Therefore, it acts like a package manager. You can also build your own libraries. Cargo is installed by default when you install Rust. To create a new cargo project, we can use the commands given below. Create a binary crate cargo new project_name –bin Create a library crate cargo new project_name –lib To check the current version of cargo, execute the following command − cargo –version Illustration – Create a Binary Cargo project The game generates a random number and prompts the user to guess the number. Step 1 – Create a project folder Open the terminal and type the following command cargo new guess-game-app –bin. This will create the following folder structure. guess-game-app/ –>Cargo.toml –>src/ main.rs The cargo new command is used to create a crate. The –bin flag indicates that the crate being created is a binary crate. Public crates are stored in a central repository called crates.io https://crates.io/. Step 2 – Include references to external libraries This example needs to generate a random number. Since the internal standard library does not provide random number generation logic, we need to look at external libraries or crates. Let us use rand crate which is available at crates.io website crates.io The rand is a rust library for random number generation. Rand provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms. The following diagram shows crate.io website and search result for rand crate. Copy the version of rand crate to the Cargo.toml file rand = “0.5.5”. [package] name = “guess-game-app” version = “0.1.0” authors = [“Mohtashim”] [dependencies] rand = “0.5.5” Step 3: Compile the Project Navigate to the project folder. Execute the command cargo build on the terminal window − Updating registry `https://github.com/rust-lang/crates.io-index` Downloading rand v0.5.5 Downloading rand_core v0.2.2 Downloading winapi v0.3.6 Downloading rand_core v0.3.0 Compiling winapi v0.3.6 Compiling rand_core v0.3.0 Compiling rand_core v0.2.2 Compiling rand v0.5.5 Compiling guess-game-app v0.1.0 (file:///E:/RustWorks/RustRepo/Code_Snippets/cargo-projects/guess-game-app) Finished dev [unoptimized + debuginfo] target(s) in 1m 07s The rand crate and all transitive dependencies (inner dependencies of rand) will be automatically downloaded. Step 4 – Understanding the Business Logic Let us now see how the business logic works for the number guessing game − Game initially generates a random number. A user is asked to enter input and guess the number. If number is less than the generated number, a message “Too low” is printed. If number is greater than the generated number, a message “Too high” is printed. If the user enters the number generated by the program, the game exits. Step 5 – Edit the main.rs file Add the business logic to main.rs file. use std::io; extern crate rand; //importing external crate use rand::random; fn get_guess() -> u8 { loop { println!(“Input guess”) ; let mut guess = String::new(); io::stdin().read_line(&mut guess) .expect(“could not read from stdin”); match guess.trim().parse::<u8>(){ //remember to trim input to avoid enter spaces Ok(v) => return v, Err(e) => println!(“could not understand input {}”,e) } } } fn handle_guess(guess:u8,correct:u8)-> bool { if guess < correct { println!(“Too low”); false } else if guess> correct { println!(“Too high”); false } else { println!(“You go it ..”); true } } fn main() { println!(“Welcome to no guessing game”); let correct:u8 = random(); println!(“correct value is {}”,correct); loop { let guess = get_guess(); if handle_guess(guess,correct){ break; } } } Step 6 – Compile and Execute the Project Execute the command cargo run on the terminal. Make sure that the terminal points to the Project directory. Welcome to no guessing game correct value is 97 Input guess 20 Too low Input guess 100 Too high Input guess 97 You got it .. Print Page Previous Next Advertisements ”;

Rust – Environment Setup

Rust – Environment Setup ”; Previous Next Installation of Rust is made easy through rustup, a console-based tool for managing Rust versions and associated tools. Installation on Windows Let us learn how to install RUST on Windows. Installation of Visual Studio 2013 or higher with C++ tools is mandatory to run the Rust program on windows. First, download Visual Studio from here VS 2013 Express Download and install rustup tool for windows. rustup-init.exe is available for download here − Rust Lang Double-click rustup-init.exe file. Upon clicking, the following screen will appear. Press enter for default installation. Once installation is completed, the following screen appears. From the installation screen, it is clear that Rust related files are stored in the folder − C:Users{PC}.cargobin The contents of the folder are − cargo-fmt.exe cargo.exe rls.exe rust-gdb.exe rust-lldb.exe rustc.exe // this is the compiler for rust rustdoc.exe rustfmt.exe rustup.exe Cargo is the package manager for Rust. To verify if cargo is installed, execute the following command − C:UsersAdmin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) The compiler for Rust is rustc. To verify the compiler version, execute the following command − C:UsersAdmin>cargo -V cargo 1.29.0 (524a578d7 2018-08-05) Installation on Linux / Mac To install rustup on Linux or macOS, open a terminal and enter the following command. $ curl https://sh.rustup.rs -sSf | sh The command downloads a script and starts the installation of the rustup tool, which installs the latest stable version of Rust. You might be prompted for your password. If the installation is successful, the following line will appear − Rust is installed now. Great! The installation script automatically adds Rust to your system PATH after your next login. To start using Rust right away instead of restarting your terminal, run the following command in your shell to add Rust to your system PATH manually − $ source $HOME/.cargo/env Alternatively, you can add the following line to your ~/.bash_profile − $ export PATH=”$HOME/.cargo/bin:$PATH” NOTE − When you try to compile a Rust program and get errors indicating that a linker could not execute, that means a linker is not installed on your system and you will need to install one manually. Using Tutorials Point Coding Ground for RUST A Read-Evaluate-Print Loop (REPL) is an easy to use interactive shell to compile and execute computer programs. If you want to compile and execute Rust programs online within the browser, use Tutorialspoint Coding Ground. Print Page Previous Next Advertisements ”;

Rust – HelloWorld Example

Rust – HelloWorld Example ”; Previous Next This chapter explains the basic syntax of Rust language through a HelloWorld example. Create a HelloWorld-App folder and navigate to that folder on terminal C:UsersAdmin>mkdir HelloWorld-App C:UsersAdmin>cd HelloWorld-App C:UsersAdminHelloWorld-App> To create a Rust file, execute the following command − C:UsersAdminHelloWorld-App>notepad Hello.rs Rust program files have an extension .rs. The above command creates an empty file Hello.rs and opens it in NOTEpad. Add the code given below to this file − fn main(){ println!(“Rust says Hello to TutorialsPoint !!”); } The above program defines a function main fn main(). The fn keyword is used to define a function. The main() is a predefined function that acts as an entry point to the program. println! is a predefined macro in Rust. It is used to print a string (here Hello) to the console. Macro calls are always marked with an exclamation mark – !. Compile the Hello.rs file using rustc. C:UsersAdminHelloWorld-App>rustc Hello.rs Upon successful compilation of the program, an executable file (file_name.exe) is generated. To verify if the .exe file is generated, execute the following command. C:UsersAdminHelloWorld-App>dir //lists the files in folder Hello.exe Hello.pdb Hello.rs Execute the Hello.exe file and verify the output. What is a macro? Rust provides a powerful macro system that allows meta-programming. As you have seen in the previous example, macros look like functions, except that their name ends with a bang(!), but instead of generating a function call, macros are expanded into source code that gets compiled with the rest of the program. Therefore, they provide more runtime features to a program unlike functions. Macros are an extended version of functions. Using the println! Macro – Syntax println!(); // prints just a newline println!(“hello “);//prints hello println!(“format {} arguments”, “some”); //prints format some arguments Comments in Rust Comments are a way to improve the readability of a program. Comments can be used to include additional information about a program like author of the code, hints about a function/ construct, etc. The compiler ignores comments. Rust supports the following types of comments − Single-line comments ( // ) − Any text between a // and the end of a line is treated as a comment Multi-line comments (/* */) − These comments may span multiple lines. Example //this is single line comment /* This is a Multi-line comment */ Execute online Rust programs can be executed online through Tutorialspoint Coding Ground. Write the HelloWorld program in the Editor tab and click Execute to view result. Print Page Previous Next Advertisements ”;

Rust – Modules

Rust – Modules ”; Previous Next A logical group of code is called a Module. Multiple modules are compiled into a unit called crate. Rust programs may contain a binary crate or a library crate. A binary crate is an executable project that has a main() method. A library crate is a group of components that can be reused in other projects. Unlike a binary crate, a library crate does not have an entry point (main() method). The Cargo tool is used to manage crates in Rust. For example, the network module contains networking related functions and the graphics module contains drawing-related functions. Modules are similar to namespaces in other programming languages. Third-party crates can be downloaded using cargo from crates.io. Sr.No Term & Description 1 crate Is a compilation unit in Rust; Crate is compiled to binary or library. 2 cargo The official Rust package management tool for crates. 3 module Logically groups code within a crate. 4 crates.io The official Rust package registry. Syntax //public module pub mod a_public_module { pub fn a_public_function() { //public function } fn a_private_function() { //private function } } //private module mod a_private_module { fn a_private_function() { } } Modules can be public or private. Components in a private module cannot be accessed by other modules. Modules in Rust are private by default. On the contrary, functions in a public module can be accessed by other modules. Modules should be prefixed with pub keyword to make it public. Functions within a public module must also be made public. Illustration: Defining a Module The example defines a public module − movies. The module contains a function play() that accepts a parameter and prints its value. pub mod movies { pub fn play(name:String) { println!(“Playing movie {}”,name); } } fn main(){ movies::play(“Herold and Kumar”.to_string()); } Output Playing movie Herold and Kumar Use Keyword The use keyword helps to import a public module. Syntax use public_module_name::function_name; Illustration pub mod movies { pub fn play(name:String) { println!(“Playing movie {}”,name); } } use movies::play; fn main(){ play(“Herold and Kumar “.to_string()); } Output Playing movie Herold and Kumar Nested Modules Modules can also be nested. The comedy module is nested within the english module, which is further nested in the movies module. The example given below defines a function play inside the movies/english/comedy module. pub mod movies { pub mod english { pub mod comedy { pub fn play(name:String) { println!(“Playing comedy movie {}”,name); } } } } use movies::english::comedy::play; // importing a public module fn main() { // short path syntax play(“Herold and Kumar”.to_string()); play(“The Hangover”.to_string()); //full path syntax movies::english::comedy::play(“Airplane!”.to_string()); } Output Playing comedy movie Herold and Kumar Playing comedy movie The Hangover Playing comedy movie Airplane! Illustration – Create a Library Crate and Consume in a Binary Crate Let us create a library crate named movie_lib, which contains a module movies. To build the movie_lib library crate, we will use the tool cargo. Step 1 – Create Project folder Create a folder movie-app followed by a sub-folder movie-lib. After the folder and sub-folder are created, create an src folder and a Cargo.toml file in this directory. The source code should go in the src folder. Create the files lib.rs and movies.rs in the src folder. The Cargo.toml file will contain the metadata of the project like version number, author name, etc. The project directory structure will be as shown below − movie-app movie-lib/ –>Cargo.toml –>src/ lib.rs movies.rs Step 2 – Edit the Cargo.toml file to add project metadata [package] name = “movies_lib” version = “0.1.0” authors = [“Mohtashim”] Step 3 – Edit the lib.rs file. Add the following module definition to this file. pub mod movies; The above line creates a public module − movies. Step 4 – Edit the movies.rs file This file will define all functions for the movies module. pub fn play(name:String){ println!(“Playing movie {} :movies-app”,name); } The above code defines a function play() that accepts a parameter and prints it to the console. Step 5 – Build the library crate Build app using the cargo build command to verify if the library crate is structured properly. Make sure you are at root of project − the movie-app folder. The following message will be displayed in the terminal if the build succeeds. D:Rustmovie-lib> cargo build Compiling movies_lib v0.1.0 (file:///D:/Rust/movie-lib) Finished dev [unoptimized + debuginfo] target(s) in 0.67s Step 6 – Create a test application Create another folder movie-lib-test in the movie-app folder followed by a Cargo.toml file and the src folder. This project should have main method as this is a binary crate, which will consume the library crate created previously. Create a main.rs file in the src folder. The folder structure will be as shown. movie-app movie-lib // already completed movie-lib-test/ –>Cargo.toml –>src/ main.rs Step 7 – Add the following in the Cargo.toml file [package] name = “test_for_movie_lib” version = “0.1.0” authors = [“Mohtashim”] [dependencies] movies_lib = { path = “../movie-lib” } NOTE − The path to the library folder is set as dependencies. The following diagram shows the contents of both the projects. Step 8 – Add the following to main.rs file extern crate movies_lib; use movies_lib::movies::play; fn main() { println!(“inside main of test “); play(“Tutorialspoint”.to_string()) } The above code imports an external package called movies_lib. Check the Cargo.toml of current project to verify the crate name. Step 9 – Use of cargo build and cargo run We will use the cargo build and cargo run to build the binary project and execute it as shown below − Print Page Previous Next Advertisements ”;

Rust – Array

Rust – Array ”; Previous Next In this chapter, we will learn about an array and the various features associated with it. Before we learn about arrays, let us see how an array is different from a variable. Variables have the following limitations − Variables are scalar in nature. In other words, a variable declaration can only contain a single value at a time. This means that to store n values in a program n variable declaration will be needed. Hence, the use of variables is not feasible when one needs to store a larger collection of values. Variables in a program are allocated memory in random order, thereby making it difficult to retrieve/read the values in the order of their declaration. An array is a homogeneous collection of values. Simply put, an array is a collection of values of the same data type. Features of an Array The features of an array are as listed below − An array declaration allocates sequential memory blocks. Arrays are static. This means that an array once initialized cannot be resized. Each memory block represents an array element. Array elements are identified by a unique integer called the subscript/ index of the element. Populating the array elements is known as array initialization. Array element values can be updated or modified but cannot be deleted. Declaring and Initializing Arrays Use the syntax given below to declare and initialize an array in Rust. Syntax //Syntax1 let variable_name = [value1,value2,value3]; //Syntax2 let variable_name:[dataType;size] = [value1,value2,value3]; //Syntax3 let variable_name:[dataType;size] = [default_value_for_elements,size]; In the first syntax, type of the array is inferred from the data type of the array’s first element during initialization. Illustration: Simple Array The following example explicitly specifies the size and the data type of the array. The {:?} syntax of the println!() function is used to print all values in the array. The len() function is used to compute the size of the array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [10, 20, 30, 40] array size is :4 Illustration: Array without data type The following program declares an array of 4 elements. The datatype is not explicitly specified during the variable declaration. In this case, the array will be of type integer. The len() function is used to compute the size of the array. fn main(){ let arr = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [10, 20, 30, 40] array size is :4 Illustration: Default values The following example creates an array and initializes all its elements with a default value of -1. fn main() { let arr:[i32;4] = [-1;4]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); } Output array is [-1, -1, -1, -1] array size is :4 Illustration: Array with for loop The following example iterates through an array and prints the indexes and their corresponding values. The loop retrieves values from index 0 to 4 (index of the last array element). fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); for index in 0..4 { println!(“index is: {} & value is : {}”,index,arr[index]); } } Output array is [10, 20, 30, 40] array size is :4 index is: 0 & value is : 10 index is: 1 & value is : 20 index is: 2 & value is : 30 index is: 3 & value is : 40 Illustration: Using the iter() function The iter() function fetches values of all elements in an array. fn main(){ let arr:[i32;4] = [10,20,30,40]; println!(“array is {:?}”,arr); println!(“array size is :{}”,arr.len()); for val in arr.iter(){ println!(“value is :{}”,val); } } Output array is [10, 20, 30, 40] array size is :4 value is :10 value is :20 value is :30 value is :40 Illustration: Mutable array The mut keyword can be used to declare a mutable array. The following example declares a mutable array and modifies value of the second array element. fn main(){ let mut arr:[i32;4] = [10,20,30,40]; arr[1] = 0; println!(“{:?}”,arr); } Output [10, 0, 30, 40] Passing Arrays as Parameters to Functions An array can be passed by value or by reference to functions. Illustration: Pass by value fn main() { let arr = [10,20,30]; update(arr); print!(“Inside main {:?}”,arr); } fn update(mut arr:[i32;3]){ for i in 0..3 { arr[i] = 0; } println!(“Inside update {:?}”,arr); } Output Inside update [0, 0, 0] Inside main [10, 20, 30] Illustration: Pass by reference fn main() { let mut arr = [10,20,30]; update(&mut arr); print!(“Inside main {:?}”,arr); } fn update(arr:&mut [i32;3]){ for i in 0..3 { arr[i] = 0; } println!(“Inside update {:?}”,arr); } Output Inside update [0, 0, 0] Inside main [0, 0, 0] Array Declaration and Constants Let us consider an example given below to understand array declaration and constants. fn main() { let N: usize = 20; let arr = [0; N]; //Error: non-constant used with constant print!(“{}”,arr[10]) } The compiler will result in an exception. This is because an array”s length must be known at compile time. Here, the value of the variable “N” will be determined at runtime. In other words, variables cannot be used to define the size of an array. However, the following program is valid − fn main() { const N: usize = 20; // pointer sized let arr = [0; N]; print!(“{}”,arr[10]) } The value of an identifier prefixed with the const keyword is defined at compile time and cannot be changed at runtime. usize is pointer-sized, thus its actual size depends on the architecture you are compiling your program for. Print Page Previous Next Advertisements ”;

Rust – Functions

Rust – Functions ”; Previous Next Functions are the building blocks of readable, maintainable, and reusable code. A function is a set of statements to perform a specific task. Functions organize the program into logical blocks of code. Once defined, functions may be called to access code. This makes the code reusable. Moreover, functions make it easy to read and maintain the program’s code. A function declaration tells the compiler about a function”s name, return type, and parameters. A function definition provides the actual body of the function. Sr.No Function & Description 1 Defining a function A function definition specifies what and how a specific task would be done. 2 Calling or invoking a Function A function must be called so as to execute it. 3 Returning Functions Functions may also return value along with control, back to the caller. 4 Parameterized Function Parameters are a mechanism to pass values to functions. Defining a Function A function definition specifies what and how a specific task would be done. Before using a function, it must be defined. The function body contains code that should be executed by the function. The rules for naming a function are similar to that of a variable. Functions are defined using the fn keyword. The syntax for defining a standard function is given below Syntax fn function_name(param1,param2..paramN) { // function body } A function declaration can optionally contain parameters/arguments. Parameters are used to pass values to functions. Example – Simple function definition //Defining a function fn fn_hello(){ println!(“hello from function fn_hello “); } Invoking a Function A function must be called so as to execute it. This process is termed as function invocation. Values for parameters should be passed when a function is invoked. The function that invokes another function is called the caller function. Syntax function_name(val1,val2,valN) Example: Invoking a Function fn main(){ //calling a function fn_hello(); } Here, the main() is the caller function. Illustration The following example defines a function fn_hello(). The function prints a message to the console. The main() function invokes the fn_hello() function. fn main(){ //calling a function fn_hello(); } //Defining a function fn fn_hello(){ println!(“hello from function fn_hello “); } Output hello from function fn_hello Returning Value from a Function Functions may also return a value along with control, back to the caller. Such functions are called returning functions. Syntax Either of the following syntax can be used to define a function with return type. With return statement // Syntax1 fn function_name() -> return_type { //statements return value; } Shorthand syntax without return statement //Syntax2 fn function_name() -> return_type { value //no semicolon means this value is returned } lllustration fn main(){ println!(“pi value is {}”,get_pi()); } fn get_pi()->f64 { 22.0/7.0 } Output pi value is 3.142857142857143 Function with Parameters Parameters are a mechanism to pass values to functions. Parameters form a part of the function’s signature. The parameter values are passed to the function during its invocation. Unless explicitly specified, the number of values passed to a function must match the number of parameters defined. Parameters can be passed to a function using one of the following techniques − Pass by Value When a method is invoked, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the invoked method have no effect on the argument. The following example declares a variable no, which is initially 5. The variable is passed as parameter (by value) to the mutate_no_to_zero()functionnction, which changes the value to zero. After the function call when control returns back to main method the value will be the same. fn main(){ let no:i32 = 5; mutate_no_to_zero(no); println!(“The value of no is:{}”,no); } fn mutate_no_to_zero(mut param_no: i32) { param_no = param_no*0; println!(“param_no value is :{}”,param_no); } Output param_no value is :0 The value of no is:5 Pass by Reference When you pass parameters by reference, unlike value parameters, a new storage location is not created for these parameters. The reference parameters represent the same memory location as the actual parameters that are supplied to the method. Parameter values can be passed by reference by prefixing the variable name with an & . In the example given below, we have a variable no, which is initially 5. A reference to the variable no is passed to the mutate_no_to_zero() function. The function operates on the original variable. After the function call, when control returns back to main method, the value of the original variable will be the zero. fn main() { let mut no:i32 = 5; mutate_no_to_zero(&mut no); println!(“The value of no is:{}”,no); } fn mutate_no_to_zero(param_no:&mut i32){ *param_no = 0; //de reference } The * operator is used to access value stored in the memory location that the variable param_no points to. This is also known as dereferencing. The output will be − The value of no is 0. Passing string to a function The main() function passes a string object to the display() function. fn main(){ let name:String = String::from(“TutorialsPoint”); display(name); //cannot access name after display } fn display(param_name:String){ println!(“param_name value is :{}”,param_name); } Output param_name value is :TutorialsPoint Print Page Previous Next Advertisements ”;