commit cc644f65692702a61518fea06dc204d2e7025356
parent 59127d6cd476916f131cfcfcf7de2dab791c9088
Author: Vetle Haflan <vetle@haflan.dev>
Date: Tue, 16 Nov 2021 21:29:11 +0100
More rust examples
Diffstat:
6 files changed, 135 insertions(+), 5 deletions(-)
diff --git a/rust/conversion.rs b/rust/conversion.rs
@@ -0,0 +1,55 @@
+// Converting between custom types uses the From trait.
+use std::fmt;
+
+struct Complex {
+ real: f32,
+ imag: f32,
+}
+
+impl fmt::Display for Complex {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ if self.imag == 0f32 {
+ write!(f, "{}", self.real)?;
+ } else {
+ write!(f, "{} + {}i", self.real, self.imag)?;
+ };
+ Ok(())
+ }
+}
+
+impl From<f32> for Complex {
+ fn from(item: f32) -> Self {
+ Complex {
+ real: item,
+ imag: 0f32,
+ }
+ }
+}
+
+fn main() {
+ // Create Complex from f32
+ let c = Complex::from(3.52);
+ println!("{}", c);
+ // Convert f32 `into` Complex
+ let ci: Complex = 8.49.into();
+ println!("{}", ci);
+
+ // try_from and try_into are alternatives that allow errors,
+ // i.e. they return Result<Self, some_error_type>.
+ // (Will probably learn more about Result in error handling chapter)
+
+ // Converting a type into a String is a special case - the `ToString` trait.
+ // Usually you implement the fmt::Display to automatically get the ToString trait
+ // and allow printing with the `print!` macros as shown in `hellow_world.rs`.
+
+ // Parsing a string
+ let string = "8";
+ let int: i32 = string.parse().unwrap();
+ //let parsed:
+ println!(
+ "size of string '{}': {}",
+ string,
+ std::mem::size_of_val(string)
+ );
+ println!("size of parsed int: {}", std::mem::size_of_val(&int));
+}
diff --git a/rust/custom_types.rs b/rust/custom_types.rs
@@ -29,10 +29,10 @@ enum StatusExplicit {
impl Status {
// Instance function
fn print(&self, prefix: String) {
- let mut str_status = match self {
- Self::InSync => String::from("all good"),
- Self::Syncing => String::from("working!"),
- Self::Error => String::from("oh no"),
+ let str_status = match self {
+ Self::InSync => "all good",
+ Self::Syncing => "working!",
+ Self::Error => "oh no",
};
println!("{} {}", prefix, str_status);
}
diff --git a/rust/expressions.rs b/rust/expressions.rs
@@ -0,0 +1,9 @@
+fn main() {
+ let res = {
+ let first = 4;
+ let squared = first * first;
+ // Last expression is assigned to res, *unless it ends with a semicolon*
+ squared - 6
+ };
+ println!("4*4-6={}", res);
+}
diff --git a/rust/flow_of_control.rs b/rust/flow_of_control.rs
@@ -0,0 +1,33 @@
+fn main() {
+ let mut opt = 2;
+ let text = if opt == 1 {
+ "option one"
+ } else if opt == 2 {
+ "option two"
+ } else {
+ "other"
+ };
+ println!("{}", text);
+ println!("NESTING AND LABELS");
+ 'outer: loop {
+ loop {
+ println!("inner, count: {}", opt);
+ opt += 1;
+ if opt > 5 {
+ break 'outer;
+ }
+ if opt > 3 {
+ break;
+ }
+ }
+ println!("outer")
+ }
+ println!("RETURNING FROM LOOP");
+ let result = loop {
+ opt += 1;
+ if opt == 10 {
+ break opt * 2;
+ }
+ };
+ assert_eq!(result, 20);
+}
diff --git a/rust/modules.rs b/rust/modules.rs
@@ -0,0 +1,16 @@
+// To create this modtest module, make a file modtest.rs or a modtest/mod.rs
+mod modtest;
+
+// Define module in block
+mod here_mod {
+ pub fn funcy(s: &str) {
+ println!("{}", s)
+ }
+}
+
+fn main() {
+ here_mod::funcy("Will print");
+ modtest::external();
+ let s = modtest::nested::nestfunc();
+ println!("{}", s)
+}
diff --git a/rust/types.rs b/rust/types.rs
@@ -1,3 +1,20 @@
fn main() {
- println!("yes");
+ println!("CASTING");
+ let decimal = 93.243_295_f32;
+ let cast_u32 = decimal as u32;
+ let cast_u8 = decimal as u8;
+ // Only u8 can be cast to char (even though char is 32 bits)
+ let cast_char = cast_u8 as char;
+ println!("u8: '{}', char: '{}'", cast_u8, cast_char);
+
+ println!("LITERALS");
+ println!("size(u8): {}", std::mem::size_of_val(&cast_u8));
+ println!("size(u32): {}", std::mem::size_of_val(&cast_u32));
+ println!("size(char): {}", std::mem::size_of_val(&cast_char));
+ println!("size(f32): {}", std::mem::size_of_val(&decimal));
+
+ println!("ALIASING");
+ type UnsignedInt128 = u128;
+ let long = 8 as UnsignedInt128;
+ println!("size(UnsignedInt128): {}", std::mem::size_of_val(&long));
}