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
Last active August 11, 2022 18:40
With scoped threads
use std::collections::HashMap;
fn main() -> Result<(), String> {
let numbers = vec![1, 2, 3, 4, 5, 6];
// This creates the scope for the threads
let (median, mode) = std::thread::scope(|scope| {
// This scoped thread calculates average
let median_thread =
@kriogenia
kriogenia / main.rs
Last active August 11, 2022 18:25
Before scoped threads
use std::collections::HashMap;
fn main() -> Result<(), String> {
let numbers = vec![1, 2, 3, 4, 5, 6];
// This thread calculates average
let median_thread =
std::thread::spawn(|| numbers.iter().sum::<i32>() as f32 / numbers.len() as f32);
// This thread calculates mode
@kriogenia
kriogenia / counter.rs
Last active July 29, 2022 11:02
&Counter implementing Add<i32> and returning Result<i32, String>
impl Add<i32> for &Counter {
type Output = Result<i32, String>;
fn add(self, rhs: i32) -> Self::Output {
let sum = self.0 + rhs;
if sum > MAX_COUNTER {
Err("Counter overflow".to_string())
} else {
Ok(i32::try_from(sum).unwrap())
}
@kriogenia
kriogenia / counter.rs
Created July 29, 2022 10:45
&Counter implementing Add<i16> and returning one i32
impl Add<i16> for &Counter {
type Output = i32;
fn add(self, rhs: i16) -> Self::Output {
self.0 + i32::from(rhs)
}
}
@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)
}
}
@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 / add.rs
Created July 28, 2022 11:32
Trait Add
pub trait Add<Rhs = Self> {
type Output;
fn add(self, rhs: Rhs) -> Self::Output;
}
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 / 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
}
@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());
}