Skip to content

Instantly share code, notes, and snippets.

View lukeabela38's full-sized avatar

Luke Abela lukeabela38

View GitHub Profile
@lukeabela38
lukeabela38 / string_slice.rs
Created August 29, 2022 17:02
Extracting a substring from a string
let s = String::from("Hello world");
let hello = &s[0..5];
let world = &s[6..11];
@lukeabela38
lukeabela38 / iterating_bytes.rs
Created August 29, 2022 16:58
Iterating over bytes in Rust
// We first pass a string by refernce
// indicating we will be returning a value of standard size
fn first_word(s: &String) -> usize {
// convert our string to bytes
let bytes = s.as_bytes();
// when we enumerate, we get both our item, and an index
// iterate over the bytes, and enumerate
@lukeabela38
lukeabela38 / passing_by_reference.rs
Created August 29, 2022 16:38
Passing Function Parameters by Reference
fn main() {
let mut s = String::from("hello");
change(&mut s);
}
fn change(mystring: &mut String) {
mystring.push_str(", world");
}
@lukeabela38
lukeabela38 / mutable_strings.rs
Created August 29, 2022 16:00
Mutable Strings in Rust
fn main () {
let mut s = String::from("hello");
s.push_str(", world"); // appeand a literal to the existing string s
println!("{}", s);
}
@lukeabela38
lukeabela38 / string_literal.rs
Created August 29, 2022 15:55
Declaration of a string Literal in Rust
{
let s = "string";
}
@lukeabela38
lukeabela38 / for_loops.rs
Created August 28, 2022 15:24
For Loops in Rust
fn main() {
// working through a predefined array
let a = [10, 20, 30, 40, 50];
for element in a {
println!("The value is {element}");
}
// generating our own data starting from 1 and ending in 4
@lukeabela38
lukeabela38 / while_loops.rs
Created August 28, 2022 14:58
The While Loop in Rust
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}!");
number -= 1;
}
@lukeabela38
lukeabela38 / loop_w_break.rs
Created August 28, 2022 14:53
A brief demo of loops and break
fn main() {
// We declare the variable as mutable to be able to change it
let mut counter = 0;
// We can declare a loop within a variable
let result = loop {
// increment our mutable value
counter += 1;
@lukeabela38
lukeabela38 / branch.rs
Created August 28, 2022 14:12
A simple example of an if statement in Rust
fn main() {
let number = 3;
if number < 5 {
println!("Smaller than 5");
} else if number > 8 {
println!("Greater than 8");
} else {
println!("Between 5 and 8");
}
@lukeabela38
lukeabela38 / function_return.rs
Created August 28, 2022 12:23
Function with return value
fn main() {
let x: i32 = 5;
let y = add_five(x);
println!("The value of y is: {y}");
}
fn add_five(a: i32) -> i32 {