Skip to content

Instantly share code, notes, and snippets.

@saiumesh535
Created September 16, 2018 18:39
Show Gist options
  • Select an option

  • Save saiumesh535/0c0ed034b9910128afbf0eaf9c2ebf5b to your computer and use it in GitHub Desktop.

Select an option

Save saiumesh535/0c0ed034b9910128afbf0eaf9c2ebf5b to your computer and use it in GitHub Desktop.
Basic types and control flow for rust
fn main() {
// defining variable
let name = "Rust!!";
println!("Welcome to {}", name);
// name = "this will throw error";
// that's beacasue by default variables are immutable
// mutation of variables
let mut i_can_mut = 1;
i_can_mut = i_can_mut + 2; // this is shadowing
println!("After mutation {}", i_can_mut);
// types for variables
let typed: u8 = 1;
println!("I'm typed {}", typed);
// const variable
// you cannot write const without type as we write for let
const IM_CONST: u32 = 8121;
println!("This is const {}", IM_CONST);
// booleans
let something = false;
println!("Hey!! this is boolean {}", something);
let is_valid: bool = true;
// what if if you want have multiple types
let multi: (u32, bool) = (IM_CONST, is_valid);
println!("This is tuple {}", multi.0);
// destructering the tuples
let (x, y) = multi;
println!("Hey! this is {x} and this is {y}", x = x, y = y);
// array
let numbers = [1,2,3,4,5];
println!("Hey!! first number is {}", numbers[0]);
// array with types
let typed_numbers: [u32; 5] = [1,2,3,4,5];
println!("Hey!! typed first number is {}", typed_numbers[1]);
// let's create a function
call_functin();
// function with params
call_functin_with_params(1,2);
// expression vs statement
let statement = 1; // this will give you a warning
// express will have it's own scope
let expression = {
let statement = 3;
statement + 1 // explicit return, so no semicolon
};
println!("the value from expression is {}", expression);
// functions with return type
let add: u32 = call_function_with_type(10,5);
println!("addtion is {}", add);
// loops
// loop {
// println!("this will run indefinately, until you hit cntrl + c");
// };
// while
let mut some_number = 3;
while some_number != 0 {
call_functin(); // called 3 times
some_number = some_number - 1;
}
// for loop
for number in numbers.iter().rev() {
println!("the number is {}", number);
}
// if and else conditions
if true {
println!("this will print always!!");
};
if 1 != 0 {
println!("hey! look there's a condition");
}
let after_condition = if 1!= 0 {
4
} else {
5
};
println!("hey!! after_condition {}", after_condition);
}
fn call_function_with_type(x: u32, y: u32) -> u32 {
x + y
}
fn call_functin_with_params(x: u32, y: u32) {
println!("the x is {x} and y is {y}", x = x, y = y);
}
fn call_functin() {
println!("Hey!! I'm called");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment