go generate

26 Aug 2017

Daigo Ikeda

Knightso, LLC

Profile

Daigo Ikeda
@hogedigo

Knightso, LLC
http://www.knightso.co.jp/
Shizuoka, JAPAN

2

go generate とは

3

用途例

4

やってみよう

5

orerr generator

こんな構造体があったときに・・・

type Sample struct {
    Name string
}
6

orerr generator

こんな構造体を生成したい

type SampleOrErr struct {
    Sample Sample
    Error  error
}
7

orerr generator

仕様

8

orerr generator

Source:

package sample

//go:generate orerr -output sample_orerr.go .

// Sampe describes sample
// +orerr
type Sample struct {
    Name string
}
9

orerr generator

実行

go generate ./...
10

go generateに使える3rd partyライブラリ

11

stringer

12

stringer

go get golang.org/x/tools/cmd/stringer

integer定数を元にString関数(fmt.Stringer)を生成

13

stringer

package painkiller

//go:generate stringer -type=Pill

type Pill int

const (
    Placebo Pill = iota
    Aspirin
    Ibuprofen
    Paracetamol
    Acetaminophen = Paracetamol
)

実行

go generate
14

stringer

同パッケージに下記コードが生成される

// Code generated by "stringer -type=Pill"; DO NOT EDIT.

package painkiller

import "fmt"

const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"

var _Pill_index = [...]uint8{0, 7, 14, 23, 34}

func (i Pill) String() string {
    if i < 0 || i >= Pill(len(_Pill_index)-1) {
        return fmt.Sprintf("Pill(%d)", i)
    }
    return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
15

gen

16

gen

go get github.com/clipperhouse/gen

genericsライクな操作をサポートする

17

gen

Source:

//go:generate jwg -output sample_json.go .

// +gen slice:"Where,Count,GroupBy[string]"
type Sample struct {
    Name string
}
18

gen

Generate:

type SampleSlice []Sample

func (rcv SampleSlice) Where(fn func(Sample) bool) (result SampleSlice)

func (rcv SampleSlice) Count(fn func(Sample) bool) (result int)

func (rcv SampleSlice) GroupByString(fn func(Sample) string) map[string]SampleSlice
19

jwg

20

jwg

go get github.com/favclip/jwg/cmd/jwg

JSONフィールドをlowerCamelCaseにする

21

jwg

Source:

//go:generate jwg -output sample_json.go .

// +jwg
type Sample struct {
    Name string
}
22

jwg

Generate:

type SampleJSON struct {
    Name string `json:"name,omitempty"`
}

他にもSample←→SampleJSON相互変換用ユーティリティ関数などが生成される

23

qbg

24

qbg

go get -u github.com/favclip/qbg/cmd/qbg

GAE/Go Datastore Query Builder

25

qbg

Before:

q := datastore.NewQuery("User")
q = q.Filter("Name =", "ikeda")
_, err = q.GetAll(ctx, &users)

After:

qb := NewUserQueryBuilder()
qb.Name.Equal("ikeda")
_, err = qb.Query().GetAll(ctx, &users)
26

まとめ

27

まとめ

Thank you!

28

Thank you

26 Aug 2017

Daigo Ikeda

Knightso, LLC

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)