Added more examples for Rust

This commit is contained in:
Eduardo Cueto Mendoza 2020-07-18 00:21:22 -06:00
parent bc133dc11e
commit b7a448ce36
4 changed files with 108 additions and 0 deletions

23
src/arrays.rs Normal file
View File

@ -0,0 +1,23 @@
use std::mem;
pub fn run() {
let mut numbers: [i32;5] = [1,2,3,4,5];
// reassign value
numbers[2] = 20;
println!("{:?}", numbers);
// Get single value
println!("Single value: {}", numbers[0]);
// Get array length
println!("Array length: {}", numbers.len());
// Arrays are stack allocated
println!("Array occupies {} bytes", mem::size_of_val(&numbers));
// Slice
let slice: &[i32] = &numbers[1..3];
println!("Slice {:?}", slice);
}

40
src/strings.rs Normal file
View File

@ -0,0 +1,40 @@
pub fn run() {
// Unmutable String type
let _hello0 = "Hello";
// Mutable String
let mut hello = String::from("Hello ");
// Get length
println!("Length: {}", hello.len());
// Push Char
hello.push('W');
// Push String
hello.push_str("orld!");
// Capacity in bytes
println!("Capacity: {}", hello.capacity());
println!("Is Empty: {}", hello.is_empty());
println!("Contains 'World' {}", hello.contains("World"));
println!("Replace {}", hello.replace("World", "There"));
for word in hello.split_whitespace() {
println!("{}",word);
}
// Create string with capacity
let mut s = String::with_capacity(10);
s.push('a');
s.push('b');
// Assertion testing
assert_eq!(2,s.len());
assert_eq!(10,s.capacity());
println!("{}", hello);
}

5
src/tuples.rs Normal file
View File

@ -0,0 +1,5 @@
pub fn run () {
let person: (&str,&str,i8) = ("Brad", "Mass", 37);
println!("{} is from {} and is {}", person.0,person.1,person.2);
}

40
src/vectors.rs Normal file
View File

@ -0,0 +1,40 @@
use std::mem;
pub fn run() {
let mut numbers: Vec<i32> = vec![1,2,3,4,5];
// reassign value
numbers[2] = 20;
// Add into vector
numbers.push(7);
// Pop off last value
numbers.pop();
println!("{:?}", numbers);
// Get single value
println!("Single value: {}", numbers[0]);
// Get array length
println!("Vector length: {}", numbers.len());
// Arrays are stack allocated
println!("Vector occupies {} bytes", mem::size_of_val(&numbers));
// Slice
let slice: &[i32] = &numbers[1..3];
println!("Slice {:?}", slice);
// Loop through vector values
for x in numbers.iter() {
println!("Number: {}",x);
}
// Loop and mutate values
for x in numbers.iter_mut() {
*x *= 2;
}
println!("Numbers vec: {:?}", numbers);
}