Skip to content

Commit

Permalink
add note about custom types
Browse files Browse the repository at this point in the history
  • Loading branch information
orsinium committed Nov 8, 2019
1 parent 40e6309 commit ee7a56e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,27 @@ doubled := genesis.SliceInt{s}.MapInt(double)

See [docs](./docs) to dive deeper.

## Custom types

Genesis contains pre-generated code for common built-in types. So, in most cases you can just use it. However, if you want to use genesis for custom types, things become a little bit more complicated. The first option is to use an empty interface. For example:

```go
type UserId int
ids := []UserId{1, 2, 3, 4, 5}
// https://github.com/golang/go/wiki/InterfaceSlice
idsInterface := make([]interface{}, len(ids), len(ids))
for i := range ids {
idsInterface[i] = ids[i]
}
index := genesis.SliceInterface{idsInterface}.FindIndex(
func(el interface{}) bool { return el.(UserId) == 3 },
)
fmt.Println(index)
// Output: 2
```

Another option is to generate genesis code for your own type.

## Generation

Install requirements
Expand Down
15 changes: 15 additions & 0 deletions genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,21 @@ import (
"github.com/life4/genesis"
)

func ExampleInterface() {
type UserId int
ids := []UserId{1, 2, 3, 4, 5}
// https://github.com/golang/go/wiki/InterfaceSlice
idsInterface := make([]interface{}, len(ids), len(ids))
for i := range ids {
idsInterface[i] = ids[i]
}
index := genesis.SliceInterface{idsInterface}.FindIndex(
func(el interface{}) bool { return el.(UserId) == 3 },
)
fmt.Println(index)
// Output: 2
}

func ExampleSliceAny() {
even := func(item int) bool { return item%2 == 0 }

Expand Down

0 comments on commit ee7a56e

Please sign in to comment.