Skip to content

Instantly share code, notes, and snippets.

View nwillc's full-sized avatar

Nwillc nwillc

View GitHub Profile
@nwillc
nwillc / splat.go
Created July 15, 2022 19:46
Go splat example
printV := func(values ...int) { fmt.Println(values) }
args := []int{1, 2, 3, 4}
printv(args...)
// output: [1 2 3 4]
@nwillc
nwillc / auto_splat.go
Created July 15, 2022 19:46
Go auto splat
fmt.Println(rotate(rotate(1, 2, 3)))
// output: 3 1 2
@nwillc
nwillc / multi_assign.go
Created July 15, 2022 19:45
Go multi assignment
aa, bb, cc = bb, cc, aa
fmt.Println(aa, bb, cc)
// output: 3 1 2
@nwillc
nwillc / multi_return.go
Created July 15, 2022 19:43
Go multiple return assignments
rotate := func(a, b, c int) (int, int, int) {
return b, c, a
}
aa, bb, cc := rotate(1, 2, 3)
fmt.Println(aa, bb, cc)
// output: 2 3 1
@nwillc
nwillc / result_example.go
Created July 15, 2022 14:22
Go Error-Result example
func foo() *Result[int] {...}
func fooBar() *Result[string] {
return Map(foo(), func(i int) *Result[string] {
return NewResult(fmt.Print(i))
})
}
@nwillc
nwillc / result.go
Created July 15, 2022 14:21
Go Error-Result pattern example
type Result[T any] struct {
//...
}
// NewResult for a value.
func NewResult[T any](t T) *Result[T] {...}
// NewResultError creates a Result from a value, error tuple.
func NewResultError[T any](t T, err error) *Result[T] {...}
// NewError for an error.
@nwillc
nwillc / go_json.go
Created July 15, 2022 14:20
Go JSON signatures
// This returns a single error and mutates v!
func json.Unmarshal(data []byte, v any) error {}
// This mutates b and returns an int and an error.
func (f *File) os.ReadAt(b []byte, off int64) (n int, err error)
@nwillc
nwillc / error_pattern.go
Created July 15, 2022 14:19
Go standard error pattern...
func foo() (int, error) {...}
func fooBar() (string, error) {
value, err := foo()
if err != nil {
return 0, err
}
// ...
return fmt.Print(value), nil
}
@nwillc
nwillc / sequence_funcs.go
Last active July 15, 2022 14:18
Go generics sequence signatures
// All returns true if all elements in the sequence match the predicate.
func All[T any](sequence Sequence[T], predicate func(t T) bool) bool {...}
// Any returns true if any element of the sequence matches the predicate.
func Any[T any](sequence Sequence[T], predicate func(t T) bool) bool {...}
// Compare two sequences with a comparator returning less/equal/greater (-1/0/1) and return comparison of the two.
func Compare[T any](s1, s2 Sequence[T], comparator func(t1, t2 T) int) int {...}
// Find returns the first element matching the given predicate, or Result error of NoSuchElement if not found.
@nwillc
nwillc / nil_panic.go
Created July 14, 2022 14:57
Crude solution to nil panic
func CaculateSomething(i int) (result int, err error) {
// Does a bunch of math to calculate a value, or
// returns an error when it can't.
done := false
defer func() {
if !done {
err = fmt.Errorf("panic: %+v", recover())
}
}()
// ... the magic ...