Skip to content

Instantly share code, notes, and snippets.

View trait_overload2.rs
trait Position<T> {
fn pos(&self) -> T;
}
struct Location {
lat: f32,
lon: f32,
}
impl Position<String> for Location {
View trait_overload1.rs
trait Nameable<T> {
fn set_name(&mut self, T);
}
struct Cyborg{
name: Option<String>,
}
impl Nameable<&str> for Cyborg {
fn set_name(&mut self, s: &str) {
View trait_operator.rs
struct Sponge {
name: String,
}
impl std::ops::Add for Sponge {
type Output = Self;
fn add(self, other: Self) -> Self {
Sponge {
name: self.name + "X" + &other.name,
}
View trait_mixin2.rs
trait SurelyNot {
fn can_we_build_it(&self);
}
impl SurelyNot for String {
fn can_we_build_it(&self) {
println!("Yes we can");
}
}
fn main() {
View trait_mixin1.rs
struct StdoutLogger {}
impl std::fmt::Display for StdoutLogger {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "I am StdoutLogger")
}
}
fn main() {
let l = StdoutLogger {};
View trait_abc.rs
trait Logger {
fn log(&self, s: &str);
fn err(&self, e: &str) {
self.log(e);
}
}
struct StdoutLogger {}
impl Logger for StdoutLogger {
View trait_interface.rs
trait Logger {
fn log(&self, s: &str);
fn err(&self, e: &str);
}
struct StdoutLogger {}
impl Logger for StdoutLogger {
fn log(&self, s: &str) {
println!("{}", s);
@grahamking
grahamking / errs.go
Created May 22, 2020
Collect and handle multiple errors in Go
View errs.go
package util
import (
"errors"
"strings"
)
// Errs is an error that collects other errors, for when you want to do
// several things and then report all of them.
type Errs struct {
View alloc.s
.text
.global _start
_start:
mov $12, %rax # brk syscall number
mov $0, %rdi # 0 is invalid, want to get current position
syscall
mov %rax, %rsi # rsi now points to start of heap mem we'll allocate
@grahamking
grahamking / slicemap_test.go
Created Jun 30, 2015
Benchmark comparing map access vs slice search
View slicemap_test.go
package main
import (
"math/rand"
"testing"
"time"
)
const (
numItems = 100 // change this to see how number of items affects speed