Publishing the syntax I learn in rust, so I can keep my thinking as clear as possible.
I will update the article whenever I learn new syntax
Rust playground: https://play.rust-lang.org/
Strings
- Rust has 2 types for strings,
str
andString
.String
is a growable, heap-allocated data structure.str
is an immutable fixed-length string somewhere in memory.
let word1: &str = "vidya mandir";
let word2: String = "sahyadri parvat".to_string();
println!("{:?} {:?}", word1, word2);
println!("{:?}", variable_name)
prints integers, strings, vectors
Array/Vector
let mut vector1 = vec![34,35,60,40,15]; // create vector, mut == vector1 is mutable/modifiable
vector1[3]; // get element at index 3
vector1.push(47); // push element to vector
vector1.pop(); // remove last element of the vector
vector1.len(); // get length of vector
println!("{:?}", vector1); // print vector
// array with length 50 and all elements equal to 0
let vector2: [u16; 50] = [0; 50];
Convert
- Number to String
let num1: u128 = 34034;
let num1_str: String = num1.to_string();
- String to Number
let num2_str: String = "40304".to_string();
let num2: u128 = num2_str.parse().unwrap();
- Combine strings
let a = "a";
let line = format!("{} + {}", a, "b");
println!("{:?}", line); // a + b
- String to number-array
// split string to form a array of vectors
let numsInStr = "3 4 25 90 233".to_string();
let numsInVec: Vec<u32> = numsInStr
.trim().split(' ')
.map(|s| s.parse().unwrap())
.collect();
println!("{:?}", numsInVec);
Loops
- for loop
let arr1 = vec![34, 50, 90, 110];
for i in 0..arr1.len() {
println!("{:?}", i);
}
Top comments (0)