Skip to content

Latest commit

 

History

History
113 lines (82 loc) · 2.32 KB

File metadata and controls

113 lines (82 loc) · 2.32 KB

Rust Basic Methods

A small reference for the most common methods.


Vec<T> Description:

  • vec.push(value) Add one item to the end.
  • vec.pop() Remove the last item.
  • vec.remove(index) Remove one item by index.
  • vec.len() Number of items.
  • vec.first() First item.
  • vec.last() Last item.
  • vec.iter() Read all items with Borrow,Doesn't take Ownership.

Example

let mut vec = vec![1, 2, 3];

vec.push(4);
vec.pop();
vec.remove(0);

println!("{}", vec.len());
println!("{:?}", vec.first());
println!("{:?}", vec.last());

for item in vec.iter() {
    println!("{}", item);
}

String Description:

  • text.push('A') Add one char.
  • text.push_str("Ali") Add one string.
  • text.trim() Remove spaces at start and end.
  • text.parse::<i32>() Change text to another type.

Example

let mut text = String::from("Ali");

text.push('!');
text.push_str(" Rust");

let clean = text.trim();

let number = "20".parse::<i32>().unwrap();

Clone Description :

value.clone() Make a new copy.

Example

let a = String::from("Ali");
let b = a.clone();

iter, iter_mut and without iter

iter
// make Borrowing to read items.
for item in vec_name.iter() {
    println!("{:?}", item);
}
without iter
// take Ownership from Vec.
for item in vec_name {
    println!("{:?}", item);
}
iter_mut
// reads item with &mut
for item in vec_name.iter_mut() {
    *item += 1; // change values
}

Quick Notes

  • push() → Add one item.
  • push_str() → Add one string.
  • pop() → Remove last item.
  • remove() → Remove by index.
  • len() → Number of items.
  • first() → First item.
  • last() → Last item.
  • iter() → Read all items without taking Ownership.
  • trim() → Remove spaces.
  • parse() → Change type.
  • clone() → Make a new copy.