DEV Community

Mahesh
Mahesh

Posted on • Updated on

Learning Rust

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 and String. 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);
Enter fullscreen mode Exit fullscreen mode

print

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]; 
Enter fullscreen mode Exit fullscreen mode

Convert

  • Number to String
let num1: u128 = 34034;
let num1_str: String = num1.to_string();
Enter fullscreen mode Exit fullscreen mode
  • String to Number
let num2_str: String = "40304".to_string();
let num2: u128 = num2_str.parse().unwrap();
Enter fullscreen mode Exit fullscreen mode
  • Combine strings
let a = "a";
let line = format!("{} + {}", a, "b");
println!("{:?}", line); // a + b
Enter fullscreen mode Exit fullscreen mode
  • 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);
Enter fullscreen mode Exit fullscreen mode

Loops

  • for loop
let arr1 = vec![34, 50, 90, 110];
for i in 0..arr1.len() {
    println!("{:?}", i);
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)