Different ways to use println! macro in Rust

·

3 min read

Print line which will just print something , but it is not as simple as we see it . It has various types within itself.

Printing a variable

fn main() {
    let a = 10 ; 
    println!("The value of the variable a is: {} " , a );
    //The fn main() indicates the starting of code .These {} should be
    // at the start of an code or at the end of a code.
    //the let is a keyword used to assign a variable a value.
    //<- This double slash means it is a comment. The compiler does not 
    //care about these. So the parenthesis in side the braces is to print the 
    //value of the variable 'a'. At the end of every statement you need 
    //place a ; semicolon in rust.
}

Printing arrays , tuples , vectors

For printing an Array we need create an array as such.

Arrays should have only one type of data in them. For example 1 , 45 , 65 etc .Their length is fixed and cannot be grown.

fn main() { 
    let b = [ 1 , 2 , 3 , 4 , 5 ]; 
    println!("The array is {:?}" , b);
   // if you but these [] sq braces it will indicate an array
   //While printing an array you need to put : and ? so that the 
   //compiler knows it is an array 
}

In this we assign the variable "b" to an array . When the code is run it will print the array.

Now we are going to print an tuple . A tuple can have different data types in them like 2.0 , "hello" , 3 etc. The same for tuple the length is fixed and cannot grow.

fn main() { 
    let a = ( 23 , 6.7 , 7.6 , 32 ); 
    println!("The tuple is {:?}" , a ); 
    //If you put the parenthesis an put values inside it they represent 
    // a tuple . For tuple too you need to put : and ? 

}

In here we assign the variable "a" to a tuple . When the code is run it will print the tuple.

Now lets print an vector.

fn main() {
     let c = vec![3 , 5 , 6 , 7 , 10];
     println!("The vector is {:?} " , c); 
    //for representing a vector you need put vec! infront of the [] sq
    //braces. For vestor too you need to put : and ?
}

Here we assign the variable "c" to a vector using vec! . When the code is run it will print the vector.

So there are many more types of printing so for more please comment bye.