The rust's syntax
So in every Programming language all programs have at starting point , it varies from each language . In rust it stars with function main(). It marks the starting point of every rust code . So in whatever rust code we can see this function main. So the most basic program in every language is printing "Hello world" . So let's do it
fn main() {
println!("Hello world");
}
here as we can see we started from " fn main() " which indicates the starting point . The keyword println! is used to print anything inside the parenthesis with double quotation .
Now let's assign a value to an variable
So for assigning an value to a variable , we have to use an keyword named 'let' . So this keyword allows us to assign a value to a variable .
fn main () {
let x = 23 ; // <- This double slash in rust means it is an comment.
// Rust doesn't care about anything behind these slashes.
// the semicolon after 23 is very essential as it marks the
// end of an statement else an error will pop up
}
So here we assign the value x to 23 .
Printing the value of a assigned variable
Now we have seen about assigning a value to a variable . Now let's see how to print a variable.
fn main() {
let x: i32 = 46 ;
println!("The value of x is : {} " , x );
// ^^^ ^^^
// The curly braces is were the value of the varible after the
// comma is printed
}
Here we assign a value 46 to the variable x. The : i32 after x tells the compiler it is an integer . It isn't necessary , there are also other integer types like i8 , i16 , i64 according to the no of bits and bytes they take.
Mutability of variable
A mutable variable means it's value can be changed again . But a an immutable variables value cannot change if assigned .
fn main() {
let mut x = 23; // Rust's variables are immutable in default
// ^^^^ The 'mut' is the keyword for making a mutable variable
println!("X is {} ", x);
x = 34 ;// Mutable variable
println!("X is {} ", x);
}
Exercise : 1. Print a string with an output : Rust is amazing .
2. Assign a value to a variable and print it .
Make a mutable variable print it and change it's value and try printing it.
Note :
Please kindly check the previous Rust Basics article series for updates now an then.