Immutable Variables vs Constant in RUST
https://www.google.com/imgres?imgurl=https%3A%2F%2Fupload.wikimedia.org%2Fwikipedia%2Fcommons%2Fthumb%2Fd%2Fd5%2FRust_programming_language_black_logo.svg%2F2048px-Rust_programming_language_black_logo.svg.png&imgrefurl=https%3A%2F%2Fcommons.wikimedia.

Immutable Variables vs Constant in RUST

Variables are immutable in Rust and so are constants. If so, why do we have them both and what is the purpose? Let's get into it.

#RustADay

Variables are by default immutable in RUST. The immutable nature of the variables can be changed by using the keyword "mut". But the constants remain the same throughout the life of the program.


let varA : u32 = 100 //The variable is immutable
let mut varB : u32 = 200 // This makes the variable mutable

const VARC : u32 = 300 // This is forever immutable        

A point to note. During the reassignment of a mutable variable, the data type cannot be changed. For example, we cannot mutate a u32 variable with a string assignment

let mut x = 5;
? ? x="Apple";

This will throw the following compilation error:
x="Apple"
? |? ? ? ?^^^^^^^ expected integer, found `&str`;        

要查看或添加评论,请登录

Raj Arun的更多文章

社区洞察

其他会员也浏览了