Compare commits

...

9 Commits

61 changed files with 586 additions and 30 deletions

View File

@@ -1,11 +1,6 @@
/custom_types/* *.d/out
/hello/* *.d/**/out
/primitives/* expression
/variable_bindings/* hello
/types/* primitives
variable_bindings
!/custom_types/*.rs
!/hello/*.rs
!/primitives/*.rs
!/variable_bindings/*.rs
!/types/*.rs

View File

@@ -0,0 +1,18 @@
use std::convert::From;
#[allow(dead_code)]
#[derive(Debug)]
struct Number {
value: i32,
}
impl From<i32> for Number {
fn from(item: i32) -> Self {
Number { value: item }
}
}
fn main() {
let num = Number::from(30);
println!("My number is {:?}", num);
}

View File

@@ -0,0 +1,19 @@
use std::convert::Into;
#[allow(dead_code)]
#[derive(Debug)]
struct Number {
value: i32,
}
impl Into<Number> for i32 {
fn into(self) -> Number {
Number { value: self }
}
}
fn main() {
let int = 5;
let num: Number = int.into();
println!("My number is {:?}", num);
}

View File

@@ -0,0 +1,16 @@
use std::fmt;
struct Circle {
radius: i32,
}
impl fmt::Display for Circle {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Circle of radius {}", self.radius)
}
}
fn main() {
let circle = Circle { radius: 6 };
println!("{}", circle.to_string());
}

View File

@@ -0,0 +1,7 @@
fn main() {
let parsed: i32 = "5".parse().unwrap();
let turbo_parsed = "10".parse::<i32>().unwrap();
let sum = parsed + turbo_parsed;
println!("Sum: {:?}", sum);
}

View File

@@ -0,0 +1,28 @@
use std::convert::TryFrom;
use std::convert::TryInto;
#[derive(Debug, PartialEq)]
struct EvenNumber(i32);
impl TryFrom<i32> for EvenNumber {
type Error = ();
fn try_from(value: i32) -> Result<Self, Self::Error> {
if value % 2 == 0 {
Ok(EvenNumber(value))
} else {
Err(())
}
}
}
fn main() {
assert_eq!(EvenNumber::try_from(8), Ok(EvenNumber(8)));
assert_eq!(EvenNumber::try_from(5), Err(()));
let result: Result<EvenNumber, ()> = 8i32.try_into();
assert_eq!(result, Ok(EvenNumber(8)));
let result: Result<EvenNumber, ()> = 5i32.try_into();
assert_eq!(result, Err(()));
}

View File

@@ -1,3 +1,4 @@
#[allow(dead_code)]
#[derive(Debug)] #[derive(Debug)]
struct Person { struct Person {
name: String, name: String,

View File

@@ -0,0 +1,25 @@
#[allow(path_statements)]
#[allow(unused_must_use)]
fn main() {
let x = 5;
x;
x + 1;
15;
let x = 5u32;
let y = {
let x_squared = x * x;
let x_cube = x_squared * x;
x_cube + x_squared + x
};
let z = {
2 * x;
};
println!("x is {:?}", x);
println!("y is {:?}", y);
println!("z is {:?}", z);
}

View File

@@ -0,0 +1,13 @@
fn main() {
for n in 1..101 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}

View File

@@ -0,0 +1,13 @@
fn main() {
for n in 1..=100 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
}
}

View File

@@ -0,0 +1,12 @@
fn main() {
let names = vec!["Bob", "Frank", "Ferris"];
for name in names.iter() {
match name {
&"Ferris" => println!("There is a rustacean among us!"),
_ => println!("Hello {}", name),
}
}
println!("names: {:?}", names);
}

View File

@@ -0,0 +1,12 @@
fn main() {
let names = vec!["Bob", "Frank", "Ferris"];
for name in names.into_iter() {
match name {
"Ferris" => println!("There is a rustacean among us!"),
_ => println!("Hello {}", name),
}
}
//println!("names: {:?}", names);
}

View File

@@ -0,0 +1,12 @@
fn main() {
let mut names = vec!["Bob", "Frank", "Ferris"];
for name in names.iter_mut() {
*name = match name {
&mut "Ferris" => "There is a rustacean among us!",
_ => "Hello",
}
}
println!("names: {:?}", names);
}

View File

@@ -0,0 +1,23 @@
fn main() {
let n = 5;
if n < 0 {
print!("{} is negative", n);
} else if n > 0 {
print!("{} is positive", n);
} else {
print!("{} is zero", n);
}
let big_n = if n < 10 && n > -10 {
println!(", and is a small number, increase net-fold");
10 * n
} else {
println!(", and is a big number, halve the number");
n / 2
};
println!("{} -> {}", n, big_n);
}

View File

@@ -0,0 +1,25 @@
fn main() {
let number = Some(7);
let letter: Option<i32> = None;
let emoticon: Option<i32> = None;
if let Some(i) = number {
println!("Matched {:?}!", i);
}
if let Some(i) = letter {
println!("Matched {:?}!", i);
} else {
println!("Didn't match a number. Let's go with a letter!");
}
let i_like_letters = false;
if let Some(i) = emoticon {
println!("Matched {:?}!", i);
} else if i_like_letters {
println!("Didn't match a number. Let's go with a letter!");
} else {
println!("I don't like letters. Let's go with an emoticon :)!");
}
}

View File

@@ -0,0 +1,27 @@
enum Foo {
Bar,
Baz,
Qux(u32),
}
fn main() {
let a = Foo::Bar;
let b = Foo::Baz;
let c = Foo::Qux(100);
if let Foo::Bar = a {
println!("a is a foobar");
}
if let Foo::Bar = b {
println!("b is foobar");
}
if let Foo::Qux(value) = c {
println!("c is {}", value);
}
if let Foo::Qux(value @ 100) = c {
println!("c is one hundred (value: {:?})", value);
}
}

View File

@@ -0,0 +1,11 @@
enum Foo {
Bar,
}
fn main() {
let a = Foo::Bar;
if let Foo::Bar = a {
println!("a is foobar");
}
}

View File

@@ -0,0 +1,16 @@
use std::str::FromStr;
fn get_count_item(s: &str) -> (u64, &str) {
let mut it = s.split(' ');
let (Some(count_str), Some(item)) = (it.next(), it.next()) else {
panic!("Can't segment count item pair: '{s}'");
};
let Ok(count) = u64::from_str(count_str) else {
panic!("Can't parse integer: '{count_str}'");
};
(count, item)
}
fn main() {
assert_eq!(get_count_item("3 chairs"), (3, "chairs"));
}

View File

@@ -0,0 +1,18 @@
#![allow(unreachable_code)]
#![allow(unused_labels)]
fn main() {
'outer: loop {
println!("Entered the outer loop");
'inner: loop {
println!("Entered the inner loop");
break 'outer;
}
println!("This point will never be reached");
}
println!("Exited the outer loop");
}

View File

@@ -0,0 +1,13 @@
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
assert_eq!(result, 20);
}

View File

@@ -0,0 +1,23 @@
fn main() {
let mut count = 0u32;
println!("Let's count until infinity!");
loop {
count += 1;
if count == 3 {
println!("three");
continue;
}
println!("{}", count);
if count == 5 {
println!("OK, that's enough");
break;
}
}
}

View File

@@ -0,0 +1,14 @@
fn age() -> u32 {
15
}
fn main() {
println!("Tell me what type of person you are");
match age() {
0 => println!("I haven't celebrated my first birthday yet"),
n @ 1..=12 => println!("I'm a child of age {:?}", n),
n @ 13..=19 => println!("I'm a teen of age {:?}", n),
n => println!("I'm an old person of age {:?}", n),
}
}

View File

@@ -0,0 +1,11 @@
fn some_number() -> Option<u32> {
Some(42)
}
fn main() {
match some_number() {
Some(n @ 42) => println!("The Answer: {}!", n),
Some(n) => println!("Not interesting... {}", n),
_ => (),
}
}

View File

@@ -0,0 +1,30 @@
#[allow(dead_code)]
enum Color {
Red,
Blue,
Green,
RGB(u32, u32, u32),
HSV(u32, u32, u32),
HSL(u32, u32, u32),
CMY(u32, u32, u32),
CMYK(u32, u32, u32, u32),
}
fn main() {
let color = Color::RGB(122, 17, 40);
println!("What color is it?");
match color {
Color::Red => println!("The color is Red!"),
Color::Blue => println!("The color is Blue!"),
Color::Green => println!("The color is Green!"),
Color::RGB(r, g, b) => println!("Red: {}, green: {}, and blue: {}!", r, g, b),
Color::HSV(h, s, v) => println!("Hue: {}, saturation: {}, value: {}!", h, s, v),
Color::HSL(h, s, l) => println!("Hue: {}, saturation: {}, lightness: {}!", h, s, l),
Color::CMY(c, m, y) => println!("Cyan: {}, magenta: {}, yellow: {}!", c, m, y),
Color::CMYK(c, m, y, k) => println!(
"Cyan: {}, magenta: {}, yellow: {}, key (black): {}!",
c, m, y, k
),
}
}

View File

@@ -0,0 +1,29 @@
fn main() {
let reference = &4;
match reference {
&val => println!("Got a value via destructuring: {:?}", val),
}
match *reference {
val => println!("Got a value via dereferencing: {:?}", val),
}
let _not_a_reference = 3;
let ref _is_a_reference = 3;
let value = 5;
let mut mut_value = 6;
match value {
ref r => println!("Got a reference to a value: {:?}", r),
}
match mut_value {
ref mut m => {
*m += 10;
println!("We added 10. `mut_value`: {:?}", m);
}
}
}

View File

@@ -0,0 +1,27 @@
fn main() {
let array = [1, -2, 6];
match array {
[0, second, third] => println!("array[0] = 0, array[1] = {}, array[2] = {}", second, third),
[1, _, third] => println!(
"array[0] = 1, array[2] = {} and array[1] was ignored",
third
),
[-1, second, ..] => println!(
"array[0] = -1, array[1] = {} and all the other ones were ignored",
second
),
[3, second, tail @ ..] => println!(
"array[0] = 3, array[1] = {} and the other elements were {:?}",
second, tail
),
[first, middle @ .., last] => println!(
"array[0] = {}, middle = {:?}, array[2] = {}",
first, middle, last
),
}
}

View File

@@ -0,0 +1,19 @@
fn main() {
struct Foo {
x: (u32, u32),
y: u32,
}
let foo = Foo { x: (1, 2), y: 3 };
match foo {
Foo { x: (1, b), y } => println!("First of x is 1, b = {}, y = {}", b, y),
Foo { y: 2, x: i } => println!("y is 2, i = {:?}", i),
Foo { y, .. } => println!("y = {}, we don't care about x", y),
}
let faa = Foo { x: (1, 2), y: 3 };
let Foo { x: x0, y: y0 } = faa;
println!("Outside: x0 = {x0:?}, y0 = {y0}");
}

View File

@@ -0,0 +1,12 @@
fn main() {
let triple = (0, -2, 3);
println!("Tell me about {:?}", triple);
match triple {
(0, y, z) => println!("First is `0`, `y` is {:?}, and `z` is {:?}", y, z),
(1, ..) => println!("First is `1` and the rest doesn't matter"),
(.., 2) => println!("last is `2` and the rest doesn't matter"),
(3, .., 4) => println!("First is `3`, last is `4`, and the rest doesn't matter"),
_ => println!("It doesn't matter what they are"),
}
}

View File

@@ -0,0 +1,16 @@
#[allow(dead_code)]
enum Temperature {
Celsius(i32),
Fahrenheit(i32),
}
fn main() {
let temperature = Temperature::Celsius(35);
match temperature {
Temperature::Celsius(t) if t > 30 => println!("{}C is above 30 Celsius", t),
Temperature::Celsius(t) => println!("{}C is below 30 Celsius", t),
Temperature::Fahrenheit(t) if t > 86 => println!("{}F is above 86 Fahrenheit", t),
Temperature::Fahrenheit(t) => println!("{}F is below 86 Fahrenheit", t),
}
}

View File

@@ -0,0 +1,9 @@
fn main() {
let number: u8 = 4;
match number {
i if i == 0 => println!("Zero"),
i if i > 0 => println!("Greater than zero"),
_ => unreachable!("Should never happen."),
}
}

View File

@@ -0,0 +1,19 @@
fn main() {
let number = 13;
println!("Tell me about {}", number);
match number {
1 => println!("One!"),
2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
13..=19 => println!("A teen"),
_ => println!("Ain't special"),
}
let boolean = true;
let binary = match boolean {
false => 0,
true => 1,
};
println!("{} -> {}", boolean, binary);
}

View File

@@ -0,0 +1,17 @@
fn main() {
let mut n = 1;
while n < 101 {
if n % 15 == 0 {
println!("fizzbuzz");
} else if n % 3 == 0 {
println!("fizz");
} else if n % 5 == 0 {
println!("buzz");
} else {
println!("{}", n);
}
n += 1;
}
}

View File

@@ -0,0 +1,13 @@
fn main() {
let mut optional = Some(0);
while let Some(i) = optional {
if i > 9 {
println!("Greater than 9, quit!");
optional = None;
} else {
println!("`i` is `{:?}`. Try again.", i);
optional = Some(i + 1);
}
}
}

View File

@@ -1,3 +1,4 @@
#[allow(dead_code)]
#[derive(Debug)] #[derive(Debug)]
struct Person<'a> { struct Person<'a> {
name: &'a str, name: &'a str,

View File

@@ -20,6 +20,6 @@ impl fmt::Display for List {
} }
fn main() { fn main() {
let v = List(vec![1, 2, 3]); let v = List(vec![6, 0, 6, 8, 0, 8, 9, 1, 1, 1, 3, 1, 2]);
println!("{}", v); println!("{}", v);
} }

View File

@@ -22,5 +22,14 @@ fn main() {
println!("borrow a section of the array as a slice"); println!("borrow a section of the array as a slice");
analyze_slice(&ys[1..4]); analyze_slice(&ys[1..4]);
// println!("{}", xs[5]); let empty_array: [u32; 0] = [];
assert_eq!(&empty_array, &[]);
assert_eq!(&empty_array, &[][..]);
for i in 0..xs.len() + 1 {
match xs.get(i) {
Some(xval) => println!("{}: {}", i, xval),
None => println!("Slow down! {} is too far!", i),
}
}
} }

View File

@@ -3,6 +3,8 @@ fn main() {
println!("1 - 2 = {}", 1i32 - 2); println!("1 - 2 = {}", 1i32 - 2);
println!("1e4 is {}, -2.5e-3 is {}", 1e4, -2.5e-3);
println!("true AND false is {}", true && false); println!("true AND false is {}", true && false);
println!("true OR false is {}", true || false); println!("true OR false is {}", true || false);
println!("NOT true is {}", !true); println!("NOT true is {}", !true);

View File

@@ -1,3 +1,5 @@
#[allow(unused_variables)]
#[allow(unused_assignments)]
fn main() { fn main() {
let logical: bool = true; let logical: bool = true;

View File

@@ -0,0 +1,15 @@
type NanoSecond = u64;
type Inch = u64;
type U64 = u64;
fn main() {
let nanoseconds: NanoSecond = 5 as U64;
let inches: Inch = 2 as U64;
println!(
"{} nanoseconds + {} inches = {} unit?",
nanoseconds,
inches,
nanoseconds + inches
);
}

View File

@@ -1,15 +0,0 @@
type NanoSecond = u64;
type Inch = u64;
#[allow(non_camel_case_types)]
type u64_t = u64;
fn main() {
let nanoseconds: NanoSecond = 5 as u64_t;
let inches: Inch = 2 as u64_t;
println!("{} nanoseconds + {} inches = {} unit?",
nanoseconds,
inches,
nanoseconds + inches);
}

View File

@@ -13,4 +13,3 @@ fn main() {
let shadowed_binding = 2; let shadowed_binding = 2;
println!("shadowed in outer block: {}", shadowed_binding); println!("shadowed in outer block: {}", shadowed_binding);
} }

View File

@@ -11,5 +11,5 @@ fn main() {
let _unused_variable = 3u32; let _unused_variable = 3u32;
let noisy_unused_variable = 2u32; let _noisy_unused_variable = 2u32;
} }