Skip to content

Instantly share code, notes, and snippets.

@encody
Created June 1, 2022 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save encody/3df3cc50c87c48b134f50cc83adb5222 to your computer and use it in GitHub Desktop.
Save encody/3df3cc50c87c48b134f50cc83adb5222 to your computer and use it in GitHub Desktop.
Introduction to Rust - NU Workshop
fn main() { // 'a
// Printing to the screen
println!("Hello, world!");
// Variables & mutability
let mut x: u128 = 1;
x = x + 1;
println!("x is {x}");
// Arrays, vectors, ranges, and loops
let arr = [3, 4, 5];
let mut my_vec = vec![];
my_vec.push(1);
my_vec.push(2);
my_vec.push(3);
for x in my_vec {
println!("Value: {x}");
}
for i in 0..=10 {
println!("{i}");
}
let mut x = 0;
while x < 10 {
x += 1;
println!("{x}");
}
let mut x = 0;
loop {
x += 1;
println!("{x}");
if x >= 10 {
break;
}
}
// Control flow
let val = if 3 < 4 {
println!("hello");
1
} else {
println!("goodbye");
0
};
let x: Option<i32> = Some(4);
let answer = x.unwrap();
println!("{answer}");
match x {
None => println!("x is none"),
Some(some_value) => println!("x is some({some_value})"),
}
let answer = if let Some(some_value) = x {
some_value
} else {
42
};
let v = std::env::var("MY_VAR").ok();
println!("{v:?}");
// Functions
fn my_function() {
println!("hello from my_function");
}
fn my_calculation() -> i32 {
8 + 1 * 4 / 5
}
// Functions with owned vs. borrowed arguments
fn say_hello(name: &String) {
println!("Hello, {name}!");
}
let name = "Jacob".to_string();
say_hello(&name);
say_hello(&name);
// Lifetimes
fn longest<'a>(first: &'a String, second: &'a String) -> &'a String {
if first.len() > second.len() {
first
} else {
second
}
}
let x = "very long string".to_string();
{ // 'b
let y = "shrt".to_string();
let longest_string = longest(&x, &y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment