Open In App

Rust – Literals

Last Updated : 08 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A literal is a source code that represents a fixed value and can be represented in the code without the need for computation. The compiler uses by default i32 for integers and f64 for float types/. In Rust, literals are described by adding them in the type as a suffix. 

Example:  Integer literal 6 has the type i32 written 60i32 and Float literal 6.0 has the type i64 and written as 6.0i64.

To understand an example of literal, we use the std::mem:: size_of_val(&variable). This function returns the pointed reference value in bytes.

Example 1:

Rust




/// When literals are suffixed in Rust 
fn main() {
   //integer -> 4 bytes, float -> 8 bytes
    let x = 3f32;
    let y = 6.0f64;
    println!("size of `x` is {} bytes", std::mem::size_of_val(&x));
    println!("size of `y` is {} bytes", std::mem::size_of_val(&y));
}


Output:

 

Example 2: 

Rust




// When literals are unsuffixed in Rust
fn main() {
      
    let x = 2; 
    //unsuffixed integer literal
    let y = 5.0; 
    //unsuffixed float literal
  
    println!("size of `x` is {} bytes", std::mem::size_of_val(&x));
    println!("size of `y` is {} bytes", std::mem::size_of_val(&y));
}


Output:

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads