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!

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

use std::fmt;

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 }

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 ..

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.

Common traits

In the 2015 edition of rust, if you wanted to use an external crate, what you'd do is to do extern crate dotenv in and then in the mod, you'd bring it into scope using use dotenv however in the 2018 version, that is not longer required. This doesn't apply to crates that ship w/ rustc e.g. alloc, test.