simontan.dev

Musings of a curious developer 📖

Rust notes

A list of questions that I encountered while learning rust. Noting them here for quicker access in the future!

https://doc.rust-lang.org/stable/rust-by-example/hello/print/print_debug.html

https://doc.rust-lang.org/stable/rust-by-example/hello/print/print_display.html

Note that implementing fmt::Display will also automatically provide to_string functionality.

use std::fmt;

#[derive(Debug)]
struct Complex {
real: f64,
imag: f64,
}

impl fmt::Display for Complex {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// `f` is a buffer, and this method must write the formatted string into it
write!(f, "{} + {}i", self.real, self.imag)
}
}

fn main() {
let complex = Complex { real: 3.3, imag: 7.2 };
println!("Compare complex:");
println!("Display: {}", complex);
println!("Debug: {:?}", complex);
}
// Output
Compare complex:
Display: 3.3 + 7.2i
Debug: Complex { real: 3.3, imag: 7.2 }

https://doc.rust-lang.org/book/ch05-01-defining-structs.html#creating-instances-from-other-instances-with-struct-update-syntax

https://doc.rust-lang.org/stable/rust-by-example/custom_types/structs.html

https://dev.to/hertz4/rust-module-essentials-12oi

https://users.rust-lang.org/t/solved-how-to-use-a-sibling-module/33173

https://doc.rust-lang.org/stable/rust-by-example/types/cast.html

https://doc.rust-lang.org/stable/rust-by-example/conversion/from_into.html

https://doc.rust-lang.org/stable/rust-by-example/flow_control/if_let.html

https://doc.rust-lang.org/stable/rust-by-example/fn/methods.html

The difference between static and instance methods is the self param. Note that it doesn't necessarily always need to be &self. you also access static methods using :: instead of ..

https://doc.rust-lang.org/stable/rust-by-example/fn/closures.html

https://doc.rust-lang.org/stable/rust-by-example/mod/split.html

https://doc.rust-lang.org/stable/rust-by-example/attribute.html

https://doc.rust-lang.org/stable/rust-by-example/scope/raii.html#destructor

Note you can also call the drop() function directly to drop it prematurely.

Mutability of data can be changed when ownership is transferred e.g. transferring from immutable var to a mutable var.

https://doc.rust-lang.org/stable/rust-by-example/trait.html

Common traits

https://doc.rust-lang.org/stable/rust-by-example/trait/dyn.html