Instantly share code, notes, and snippets.

View silly_fizzbuzz.go
package main
import (
"fmt"
"strconv"
)
func main() {
vals := [][]string{{"FizzBuzz", "Fizz"}, {"Buzz", ""}}
for i := 1; i <= 100; i++ {
View workpool.go
type WorkPool struct {
work chan Runnable
shutdown chan struct{}
o sync.Once
}
type Runnable func()
func NewWorkPool(tasks int) *WorkPool {
work := make(chan Runnable, tasks)
View reflection2_9.go
func AddSlowly(a, b int) int {
time.Sleep(100 * time.Millisecond)
return a + b
}
func main() {
ch, err := Cacher(AddSlowly, 2*time.Second)
if err != nil {
panic(err)
}
View reflection2_8.go
type outExp struct {
out []reflect.Value
expiry time.Time
}
func Cacher(f interface{}, expiration time.Duration) (interface{}, error) {
ft := reflect.TypeOf(f)
if ft.Kind() != reflect.Func {
return nil, errors.New("Only for functions")
}
View reflection2_7.go
func buildInStruct(ft reflect.Type) (reflect.Type, error) {
if ft.NumIn() == 0 {
return nil, errors.New("Must have at least one param")
}
var sf []reflect.StructField
for i := 0; i < ft.NumIn(); i++ {
ct := ft.In(i)
if !ct.Comparable() {
return nil, fmt.Errorf("parameter %d of type %s and kind %v is not comparable", i+1, ct.Name(), ct.Kind())
}
View reflection2_6.go
func Cacher(f interface{}, expiration time.Duration) (interface{}, error) {
ft := reflect.TypeOf(f)
if ft.Kind() != reflect.Func {
return nil, errors.New("Only for functions")
}
return f, nil
}
View reflection2_5.go
// Takes in a function and a time.Duration and returns a caching version of the function
//
// The limitations on memoization are:
//
// — there must be at least one in parameter
//
// — there must be at least one out parameter
//
// — the in parameters must be comparable. That means they cannot be of kind slice, map, or func,
// nor can input parameters be structs that contain (at any level) slices, maps, or funcs.
View reflection2_4.go
subv = v
destring = f.quoted
for _, i := range f.index {
if subv.Kind() == reflect.Ptr {
if subv.IsNil() {
subv.Set(reflect.New(subv.Type().Elem()))
}
subv = subv.Elem()
}
subv = subv.Field(i)
View reflection2_3.go
switch v.Kind() {
case reflect.Map:
// Map key must either have string kind, have an integer kind,
// or be an encoding.TextUnmarshaler.
t := v.Type()
switch t.Key().Kind() {
case reflect.String,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
default:
View reflection2_2.go
// Decoding into nil interface? Switch to non-reflect code.
if v.Kind() == reflect.Interface && v.NumMethod() == 0 {
v.Set(reflect.ValueOf(d.objectInterface()))
return
}