Rust – Ownership

Rust – Ownership ”; Previous Next The memory for a program can be allocated in the following − Stack Heap Stack A stack follows a last in first out order. Stack stores data values for which the size is known at compile time. For example, a variable of fixed size i32 is a candidate for stack allocation. Its size is known at compile time. All scalar types can be stored in stack as the size is fixed. Consider an example of a string, which is assigned a value at runtime. The exact size of such a string cannot be determined at compile time. So it is not a candidate for stack allocation but for heap allocation. Heap The heap memory stores data values the size of which is unknown at compile time. It is used to store dynamic data. Simply put, a heap memory is allocated to data values that may change throughout the life cycle of the program. The heap is an area in the memory which is less organized when compared to stack. What is Ownership? Each value in Rust has a variable that is called owner of the value. Every data stored in Rust will have an owner associated with it. For example, in the syntax − let age = 30, age is the owner of the value 30. Each data can have only one owner at a time. Two variables cannot point to the same memory location. The variables will always be pointing to different memory locations. Transferring Ownership The ownership of value can be transferred by − Assigning value of one variable to another variable. Passing value to a function. Returning value from a function. Assigning value of one variable to another variable The key selling point of Rust as a language is its memory safety. Memory safety is achieved by tight control on who can use what and when restrictions. Consider the following snippet − fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap //only a single variable owns the heap memory at any given time let v2 = v; // here two variables owns heap value, //two pointers to the same content is not allowed in rust //Rust is very smart in terms of memory access ,so it detects a race condition //as two variables point to same heap println!(“{:?}”,v); } The above example declares a vector v. The idea of ownership is that only one variable binds to a resource, either v binds to resource or v2 binds to the resource. The above example throws an error − use of moved value: `v`. This is because the ownership of the resource is transferred to v2. It means the ownership is moved from v to v2 (v2=v) and v is invalidated after the move. Passing value to a function The ownership of a value also changes when we pass an object in the heap to a closure or function. fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 display(v2); // v2 is moved to display and v2 is invalidated println!(“In main {:?}”,v2); //v2 is No longer usable here } fn display(v:Vec<i32>){ println!(“inside display {:?}”,v); } Returning value from a function Ownership passed to the function will be invalidated as function execution completes. One work around for this is let the function return the owned object back to the caller. fn main(){ let v = vec![1,2,3]; // vector v owns the object in heap let v2 = v; // moves ownership to v2 let v2_return = display(v2); println!(“In main {:?}”,v2_return); } fn display(v:Vec<i32>)->Vec<i32> { // returning same vector println!(“inside display {:?}”,v); } Ownership and Primitive Types In case of primitive types, contents from one variable is copied to another. So, there is no ownership move happening. This is because a primitive variable needs less resources than an object. Consider the following example − fn main(){ let u1 = 10; let u2 = u1; // u1 value copied(not moved) to u2 println!(“u1 = {}”,u1); } The output will be – 10. Print Page Previous Next Advertisements ”;

Scala Collections – BitSet

Scala Collections – BitSet ”; Previous Next Bitset is a common base class for mutable and immutable bitsets. Bitsets are sets of non-negative integers and are represented as variable-size arrays of bits packed into 64-bit words. The memory footprint of a bitset is represented by the largest number stored in it. Declaring BitSet Variables The following is the syntax for declaring an BitSet variable. Syntax var z : BitSet = BitSet(0,1,2) Here, z is declared as an bit-set of non-negative integers which has three members. Values can be added by using commands like the following − Command var myList1: BitSet = myList + 3; Processing BitSet Below is an example program of showing how to create, initialize and process BitSet − Example import scala.collection.immutable.BitSet object Demo { def main(args: Array[String]) = { var mySet: BitSet = BitSet(0, 1, 2); // Add an element var mySet1: BitSet = mySet + 3; // Remove an element var mySet2: BitSet = mySet – 2; var mySet3: BitSet = BitSet(4, 5); // Adding sets var mySet4: BitSet = mySet1 ++ mySet3; println(mySet); println(mySet1); println(mySet2); println(mySet4); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output BitSet(0, 1, 2) BitSet(0, 1, 2, 3) BitSet(0, 1) BitSet(0, 1, 2, 3, 4, 5) Print Page Previous Next Advertisements ”;

Scala Collections – Home

Scala Collections Tutorial PDF Version Quick Guide Resources Job Search Discussion Scala has a rich set of collection library. Scala Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items. Audience This tutorial has been prepared for the beginners to help them understand Scala Collections library to use Collections in Scala based programs. Prerequisites For this tutorial, we assume the readers to have prior knowledge of basic software development using Java or Scala. It will help if you had some exposure to the software build and deployment process. Print Page Previous Next Advertisements ”;

Scala Collections – Environment Setup

Scala Collections – Environment Setup ”; Previous Next Scala can be installed on any UNIX flavored or Windows based system. Before you start installing Scala on your machine, you must have Java 1.8 or greater installed on your computer. Follow the steps given below to install Scala. Step 1: Verify Your Java Installation First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on. If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table. Platform Command Sample Output Windows Open Command Console and type − >java -version Java version “1.8.0_31” Java (TM) SE Run Time Environment (build 1.8.0_31-b31) Java Hotspot (TM) 64-bit Server VM (build 25.31-b07, mixed mode) Linux Open Command terminal and type − $java -version Java version “1.8.0_31” Open JDK Runtime Environment (rhel-2.8.10.4.el6_4-x86_64) Open JDK 64-Bit Server VM (build 25.31-b07, mixed mode) We assume that the readers of this tutorial have Java SDK version 1.8.0_31 installed on their system. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and install it. Step 2: Set Your Java Environment Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example, Sr.No Platform & Description 1 Windows Set JAVA_HOME to C:ProgramFilesjavajdk1.8.0_31 2 Linux Export JAVA_HOME=/usr/local/java-current Append the full path of Java compiler location to the System Path. Sr.No Platform & Description 1 Windows Append the String “C:Program FilesJavajdk1.8.0_31bin” to the end of the system variable PATH. 2 Linux Export PATH=$PATH:$JAVA_HOME/bin/ Execute the command java -version from the command prompt as explained above. Step 3: Install Scala You can download Scala from www.scala-lang.org/downloads. At the time of writing this tutorial, I downloaded ”scala-2.13.1-installer.jar”. Make sure you have admin privilege to proceed. Now, execute the following command at the command prompt − Platform Command & Output Description Windows >java -jar scala-2.13.1-installer.jar> This command will display an installation wizard, which will guide you to install Scala on your windows machine. During installation, it will ask for license agreement, simply accept it and further it will ask a path where Scala will be installed. I selected default given path “C:Program FilesScala”, you can select a suitable path as per your convenience. Linux Command − $java -jar scala-2.13.1-installer.jar Output − Welcome to the installation of Scala 2.13.1! The homepage is at − http://Scala-lang.org/ press 1 to continue, 2 to quit, 3 to redisplay 1………………………………………… [ Starting to unpack ] [ Processing package: Software Package Installation (1/1) ] [ Unpacking finished ] [ Console installation done ] During installation, it will ask for license agreement, to accept it type 1 and it will ask a path where Scala will be installed. I entered /usr/local/share, you can select a suitable path as per your convenience. Finally, open a new command prompt and type Scala -version and press Enter. You should see the following − Platform Command Output Windows >scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc. Linux $scala -version Scala code runner version 2.13.1 — Copyright 2002-2019, LAMP/EPFL and Lightbend, Inc.tut Print Page Previous Next Advertisements ”;

Rust – Decision Making

Rust – Decision Making ”; Previous Next Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, along with a statement or statements to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false. Shown below is the general form of a typical decision-making structure found in most of the programming languages − Sr.No Statement & Description 1 if statement An if statement consists of a Boolean expression followed by one or more statements. 2 if…else statement An if statement can be followed by an optional else statement, which executes when the Boolean expression is false. 3 else…if and nested ifstatement You can use one if or else if statement inside another if or else if statement(s). 4 match statement A match statement allows a variable to be tested against a list of values. If Statement The if…else construct evaluates a condition before a block of code is executed. Syntax if boolean_expression { // statement(s) will execute if the boolean expression is true } If the Boolean expression evaluates to true, then the block of code inside the if statement will be executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed. fn main(){ let num:i32 = 5; if num > 0 { println!(“number is positive”) ; } } The above example will print number is positive as the condition specified by the if block is true. if else statement An if can be followed by an optional else block. The else block will execute if the Boolean expression tested by the if statement evaluates to false. Syntax if boolean_expression { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false } FlowChart The if block guards the conditional expression. The block associated with the if statement is executed if the Boolean expression evaluates to true. The if block may be followed by an optional else statement. The instruction block associated with the else block is executed if the expression evaluates to false. Illustration – Simple if…else fn main() { let num = 12; if num % 2==0 { println!(“Even”); } else { println!(“Odd”); } } The above example prints whether the value in a variable is even or odd. The if block checks the divisibility of the value by 2 to determine the same. Here is the output of the above code − Even Nested If The else…if ladder is useful to test multiple conditions. The syntax is as shown below − Syntax if boolean_expression1 { //statements if the expression1 evaluates to true } else if boolean_expression2 { //statements if the expression2 evaluates to true } else { //statements if both expression1 and expression2 result to false } When using if…else…if and else statements, there are a few points to keep in mind. An if can have zero or one else”s and it must come after any else..if. An if can have zero to many else..if and they must come before the else. Once an else..if succeeds, none of the remaining else..if or else will be tested. Example: else…if ladder fn main() { let num = 2 ; if num > 0 { println!(“{} is positive”,num); } else if num < 0 { println!(“{} is negative”,num); } else { println!(“{} is neither positive nor negative”,num) ; } } The snippet displays whether the value is positive, negative or zero. Output 2 is positive Match Statement The match statement checks if a current value is matching from a list of values, this is very much similar to the switch statement in C language. In the first place, notice that the expression following the match keyword does not have to be enclosed in parentheses. The syntax is as shown below. let expressionResult = match variable_expression { constant_expr1 => { //statements; }, constant_expr2 => { //statements; }, _ => { //default } }; In the example given below, state_code is matched with a list of values MH, KL, KA, GA − if any match is found, a string value is returned to variable state. If no match is found, the default case _ matches and value Unkown is returned. fn main(){ let state_code = “MH”; let state = match state_code { “MH” => {println!(“Found match for MH”); “Maharashtra”}, “KL” => “Kerala”, “KA” => “Karnadaka”, “GA” => “Goa”, _ => “Unknown” }; println!(“State name is {}”,state); } Output Found match for MH State name is Maharashtra Print Page Previous Next Advertisements ”;

Rexx – Variables

Rexx – Variables ”; Previous Next In Rexx, all variables are bound with the ‘=’ statement. Variable names are sometimes referred to as symbols. They may be composed of Letters, Digits, and Characters such as ‘. ! ? _’. A variable name you create must not begin with a digit or a period. A simple variable name does not include a period. A variable name that includes a period is called a compound variable and represents an array or table. The following are the basic types of variables in Rexx which were also explained in the previous chapter − Integers − This is used to represent an integer or a float. An example for this is 10. Big integers − This represents a large integer value. Decimal − A decimal value is a string of numerics that contains a decimal point but no exponent identifier. Float − A float value is a string that represents a number in the scientific notation. String − A series of characters defines a string in Rexx. Different Types of Variable Functions In this section, we will discuss regarding the various functions a variable can perform. Variable Declarations The general syntax of defining a variable is shown as follows − var-name = var-value where var-name − This is the name of the variable. var-value − This is the value bound to the variable. The following program is an example of the variable declaration − Example Live Demo /* Main program */ X = 40 Y = 50 Result = X + Y say Result In the above example, we have 2 variables, one is X which is bound to the value 40 and the next is Y which is bound to the value of 50. Another variable called Result is bound to the addition of X and Y. The output of the above program will be as follows − 90 Naming Variables Variable names are sometimes referred to as symbols. They may be composed of Letters, Digits, and Characters such as ‘. ! ? _’ . A variable name you create must not begin with a digit or period. If a variable has not yet been assigned a value, it is referred to as uninitialized. The value of an uninitialized variable is the name of the variable itself in uppercase letters. An example of an unassigned variable is as follows − Example Live Demo /* Main program */ unassignedvalue say unassignedvalue If you run the above program you will get the following output − UNASSIGNEDVALUE sh: UNASSIGNEDVALUE: command not found 2 *-* unassignedvalue >>> “UNASSIGNEDVALUE” +++ “RC(127)” Variables can be assigned values more than once. The below program shows how the value of X can be assigned a value multiple times. Example Live Demo /* Main program */ X = 40 X = 50 say X The output of the above program will be as follows − 50 Printing Variables The values of variables are printed using the say command. Following is an example of printing a variety number of variables. Example Live Demo /* Main program */ X = 40 /* Display an Integer */ say X Y = 50.5 /* Display a Float */ say Y Z = “hello” /* Display a string */ say Z The output of the above program will be as follows − 40 50.5 hello Print Page Previous Next Advertisements ”;

Scala Collections – Vector

Scala Collections – Vector ”; Previous Next Scala Vector is a general purpose immutable data structure where elements can be accessed randomly. It is generally used for large collections of data. Declaring Vector Variables The following is the syntax for declaring an Vector variable. Syntax var z : Vector[String] = Vector(“Zara”,”Nuha”,”Ayan”) Here, z is declared as an vector of Strings which has three members. Values can be added by using commands like the following − Command var vector1: Vector[String] = z + “Naira”; Processing Vector Below is an example program of showing how to create, initialize and process Vector − Example import scala.collection.immutable.Vector object Demo { def main(args: Array[String]) = { var vector: Vector[String] = Vector(“Zara”,”Nuha”,”Ayan”); // Add an element var vector1: Vector[String] = vector :+ “Naira”; // Reverse an element var vector2: Vector[String] = vector.reverse; // sort a vector var vector3: Vector[String] = vector1.sorted; println(vector); println(vector1); println(vector2); println(vector3); } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. Command >scalac Demo.scala >scala Demo Output Vector(Zara, Nuha, Ayan) Vector(Zara, Nuha, Ayan, Naira) Vector(Ayan, Nuha, Zara) Vector(Ayan, Naira, Nuha, Zara) Print Page Previous Next Advertisements ”;

Scala Collections – Overview

Scala Collections – Overview ”; Previous Next Scala has a rich set of collection library. Collections are containers of things. Those containers can be sequenced, linear sets of items like List, Tuple, Option, Map, etc. The collections may have an arbitrary number of elements or be bounded to zero or one element (e.g., Option). Collections may be strict or lazy. Lazy collections have elements that may not consume memory until they are accessed, like Ranges. Additionally, collections may be mutable (the contents of the reference can change) or immutable (the thing that a reference refers to is never changed). Note that immutable collections may contain mutable items. For some problems, mutable collections work better, and for others, immutable collections work better. When in doubt, it is better to start with an immutable collection and change it later if you need mutable ones. This chapter throws light on the most commonly used collection types and most frequently used operations over those collections. Sr.No Collections with Description 1 Scala Lists Scala”s List[T] is a linked list of type T. 2 Scala Sets A set is a collection of pairwise different elements of the same type. 3 Scala Maps A Map is a collection of key/value pairs. Any value can be retrieved based on its key. 4 Scala Tuples Unlike an array or list, a tuple can hold objects with different types. 5 Scala Options Option[T] provides a container for zero or one element of a given type. 6 Scala Iterators An iterator is not a collection, but rather a way to access the elements of a collection one by one. Print Page Previous Next Advertisements ”;

Rust – Concurrency

Rust – Concurrency ”; Previous Next In Concurrent programming, different parts of a program execute independently. On the other hand, in parallel programming, different parts of a program execute at the same time. Both the models are equally important as more computers take advantage of their multiple processors. Threads We can use threads to run codes simultaneously. In current operating systems, an executed program’s code is run in a process, and the operating system manages multiple processes at once. Within your program, you can also have independent parts that run simultaneously. The features that run these independent parts are called threads. Creating a Thread The thread::spawn function is used to create a new thread. The spawn function takes a closure as parameter. The closure defines code that should be executed by the thread. The following example prints some text from a main thread and other text from a new thread. //import the necessary modules use std::thread; use std::time::Duration; fn main() { //create a new thread thread::spawn(|| { for i in 1..10 { println!(“hi number {} from the spawned thread!”, i); thread::sleep(Duration::from_millis(1)); } }); //code executed by the main thread for i in 1..5 { println!(“hi number {} from the main thread!”, i); thread::sleep(Duration::from_millis(1)); } } Output hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the main thread! hi number 2 from the spawned thread! hi number 3 from the main thread! hi number 3 from the spawned thread! hi number 4 from the spawned thread! hi number 4 from the main thread! The main thread prints values from 1 to 4. NOTE − The new thread will be stopped when the main thread ends. The output from this program might be a little different every time. The thread::sleep function forces a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that is not guaranteed – it depends on how the operating system schedules the threads. In this run, the main thread is printed first, even though the print statement from the spawned thread appears first in the code. Moreover, even if the spawned thread is programmed to print values till 9, it only got to 5 before the main thread shut down. Join Handles A spawned thread may not get a chance to run or run completely. This is because the main thread completes quickly. The function spawn<F, T>(f: F) -> JoinHandlelt;T> returns a JoinHandle. The join() method on JoinHandle waits for the associated thread to finish. use std::thread; use std::time::Duration; fn main() { let handle = thread::spawn(|| { for i in 1..10 { println!(“hi number {} from the spawned thread!”, i); thread::sleep(Duration::from_millis(1)); } }); for i in 1..5 { println!(“hi number {} from the main thread!”, i); thread::sleep(Duration::from_millis(1)); } handle.join().unwrap(); } Output hi number 1 from the main thread! hi number 1 from the spawned thread! hi number 2 from the spawned thread! hi number 2 from the main thread! hi number 3 from the spawned thread! hi number 3 from the main thread! hi number 4 from the main thread! hi number 4 from the spawned thread! hi number 5 from the spawned thread! hi number 6 from the spawned thread! hi number 7 from the spawned thread! hi number 8 from the spawned thread! hi number 9 from the spawned thread! The main thread and spawned thread continue switching. NOTE − The main thread waits for spawned thread to complete because of the call to the join() method. Print Page Previous Next Advertisements ”;

Rust – Quick Guide

Rust – Quick Guide ”; Previous Next Rust – Introduction Rust is a systems level programming language, developed by Graydon Hoare. Mozilla Labs later acquired the programme. Application v/s Systems Programming Languages Application programming languages like Java/C# are used to build software, which provide services to the user directly. They help us build business applications like spreadsheets, word processors, web applications or mobile applications. Systems programming languages like C/C++ are used to build software and software platforms. They can be used to build operating systems, game engines, compilers, etc. These programming languages require a great degree of hardware interaction. Systems and application programming languages face two major problems − It is difficult to write secure code. It is difficult to write multi-threaded code. Why Rust? Rust focuses on three goals − Safety Speed Concurrency The language was designed for developing highly reliable and fast software in a simple way. Rust can be used to write high-level programs down to hardware-specific programs. Performance Rust programming language does not have a Garbage Collector (GC) by design. This improves the performance at runtime. Memory safety at compile time Software built using Rust is safe from memory issues like dangling pointers, buffer overruns and memory leaks. Multi-threaded applications Rust’s ownership and memory safety rules provide concurrency without data races. Support for Web Assembly (WASM) Web Assembly helps to execute high computation intensive algorithms in the browser, on embedded devices, or anywhere else. It runs at the speed of native code. Rust can be compiled to Web Assembly for fast, reliable execution. Rust – Environment Setup 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. Rust – HelloWorld Example 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 ( // )