Skip to content

Instantly share code, notes, and snippets.

@khansgithub
Created April 26, 2024 03:52
Show Gist options
  • Save khansgithub/31030340cfb33227119cc8e28cdada0f to your computer and use it in GitHub Desktop.
Save khansgithub/31030340cfb33227119cc8e28cdada0f to your computer and use it in GitHub Desktop.

import mod from file

// main.ts
mod grid;
use grid::Grid;
...
let mut grid: Grid = Grid::new();

// grid.rs
pub struct Grid{}
...

reciever functions

// new fn / constructor
impl Grid {
  fn new() -> Self{
    return Self{};
  }
}

add traits

#[derive(Debug)]

or

impl Default for Grid{}
impl fmt::Display for Grid{}

Display is similar to Debug, but Display is for user-facing output, and so cannot be derived


printing objects

#[derive(Debug)]
struct Grid{}
print!("{:?}", grid)

or

impl Display for Grid{
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result{
    write!()
  }
}

@khansgithub
Copy link
Author

print memory address

let x = false;
print!("{:p}", x);

@khansgithub
Copy link
Author

lifetimes

struct Grid<'a> {
    // the reference `foo` will live as long as the instance of Grid
    foo: &'a Vec<u8>
}
...
// anonymous lifetime must be written anytime Grid is mentioned
impl fmt::Display for Grid <'_>{...]

@khansgithub
Copy link
Author

moving

fn foo() -> String{
    // owner of this String instance is being moved 
    return String::from("foo");
}

// from the above local scope, to `x`
let x = foo();

// then it's being moved to `y`
let y = x;

// `x` has no valid reference to anything
print!("{}", x);

copy

let x: u8 = 1;

// primatives are copied, not moved
let b = x;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment