Created
June 1, 2022 18:44
-
-
Save encody/3df3cc50c87c48b134f50cc83adb5222 to your computer and use it in GitHub Desktop.
Introduction to Rust - NU Workshop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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