Skip to content

Instantly share code, notes, and snippets.

@spareslant
Last active July 28, 2021 18:50
Show Gist options
  • Save spareslant/0c792dd11e698f342355b09509b5d6c4 to your computer and use it in GitHub Desktop.
Save spareslant/0c792dd11e698f342355b09509b5d6c4 to your computer and use it in GitHub Desktop.
fn main() {
vector_1();
vector_2();
vector_3();
vector_4();
vector_5();
vector_6();
}
fn vector_1() {
println!("=========== vector_1 ===========");
let mut v = vec![1, 2, 3, 4, 5];
for i in &v {
println!("{}", i);
}
println!("---------------------");
v.push(6);
for i in &v {
println!("{}", i);
}
}
fn vector_2() {
println!("=========== vector_2 ===========");
let v = vec![1, 2, 3, 4, 5];
for i in v {
println!("{}", i);
}
// uncommenting following lines will produce compile errors.
// println!("v = {:?}", v);
// for j in &v {
// println!("{}", j);
// }
}
fn vector_3() {
println!("=========== vector_3 ===========");
let mut v = vec![1, 2, 3, 4, 5];
for i in &mut v {
*i += 50;
}
println!("value of v is {:?}", v);
}
fn vector_4() {
println!("=========== vector_4 ===========");
let mut names = vec!["astring", "london", "pizza"];
for (_i, name) in names.iter_mut().enumerate() {
println!("name = {}", name.to_ascii_uppercase());
// names.insert(i, &name.to_ascii_uppercase());
// let mut s = name.to_ascii_uppercase();
// name = &mut &s[..];
}
println!("names = {:?}", names);
}
fn vector_5() {
println!("=========== vector_5 ===========");
let mut names = vec!["astring", "london", "pizza"];
for name in names.iter_mut() {
let mut s = "ORACLE";
*name = &mut s;
}
println!("names = {:?}", names);
}
fn vector_6() {
println!("=========== vector_6 ===========");
let mut names = vec!["astring".to_string(), "london".to_string(), "pizza".to_string()];
for name in names.iter_mut() {
let s = name.to_ascii_uppercase();
*name = s;
}
println!("names = {:?}", names);
}
// ******** OUTPUT *******
//
// =========== vector_1 ===========
// 1
// 2
// 3
// 4
// 5
// ---------------------
// 1
// 2
// 3
// 4
// 5
// 6
// =========== vector_2 ===========
// 1
// 2
// 3
// 4
// 5
// =========== vector_3 ===========
// value of v is [51, 52, 53, 54, 55]
// =========== vector_4 ===========
// name = ASTRING
// name = LONDON
// name = PIZZA
// names = ["astring", "london", "pizza"]
// =========== vector_5 ===========
// names = ["ORACLE", "ORACLE", "ORACLE"]
// =========== vector_6 ===========
// names = ["ASTRING", "LONDON", "PIZZA"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment