Skip to content

Instantly share code, notes, and snippets.

View kriogenia's full-sized avatar

Soto Estévez kriogenia

View GitHub Profile
@kriogenia
kriogenia / main.rs
Created June 3, 2022 12:49
enumerate
fn main() {
let vec = vec!["f", "o", "o"];
// instead of this
for i in 0..vec.len() {
println!("The character at {i} is {}", vec[i]);
}
// you can use this
for (i, char) in vec.iter().enumerate() {
println!("The character at {i} is {char}");
}
struct Foo {
bar: i32
}
impl Foo {
fn instead_of_this() -> Foo {
Foo { bar: 0 }
}
fn you_can_use_this() -> Self {
@kriogenia
kriogenia / main.rs
Last active June 17, 2022 16:07
Starting point of Dynamic tuple indices in Rust
use std::{rc::Rc, cell::RefCell};
struct XLimit {
vector: Rc<RefCell<(i32, i32)>>,
limit: i32
}
impl XLimit {
fn limit(&self) {
if (*self.vector).borrow().0 > self.limit {
@kriogenia
kriogenia / main.rs
Last active June 17, 2022 16:44
Dynamic tuple access in Rust
use std::{rc::Rc, cell::RefCell};
macro_rules! nth {
($tuple:expr, $axis:tt) => {
match $axis {
0 => $tuple.0,
1 => $tuple.1,
_ => unreachable!()
}
}
@kriogenia
kriogenia / main.rs
Created June 22, 2022 19:32
Using mod.rs
mod calc;
mod foo;
fn main() {
assert!(foo::bar());
assert_eq!(2, calc::mul::mul(2, calc::mul::MUL_IDENTITY));
println!("{}", calc::hello());
}
@kriogenia
kriogenia / calc.rs
Created June 22, 2022 20:07
Using <module>.rs
pub mod mul;
mod strings; // Hidden to the outside world
pub fn hello() -> &'static str {
strings::HELLO
}
mod mul; // Now it's hidden too
pub use mul::mul; // But we can still access this function
mod strings;
pub fn hello() -> &'static str {
strings::HELLO
}
@kriogenia
kriogenia / add.rs
Created July 28, 2022 11:32
Trait Add
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
@kriogenia
kriogenia / counter.rs
Created July 28, 2022 11:55
Counter implementing Add Self
impl Add for Counter {
type Output = Counter;
fn add(self, rhs: Self) -> Self::Output {
Self(self.0 + rhs.0)
}
}
@kriogenia
kriogenia / counter.rs
Created July 29, 2022 07:07
&Coutner implementing Add<Self>
impl Add for &Counter {
type Output = Counter;
fn add(self, rhs: Self) -> Self::Output {
Counter(self.0 + rhs.0)
}
}