go-typeswitch-gen

Expands type switches with type variables to achieve generic functions in Golang

Stars
34

= go-typeswitch-gen

== INSTALLATION

go get github.com/motemen/go-typeswitch-gen/cmd/tsgen

== USAGE

tsgen [-w] [-main ] [-verbose]

Modes: expand: expand generic case clauses in type switch statements by its actual arguments scaffold: generate stub case clauses based on types that implement subject interface sort: sort case clauses in type switch statements

Flags: -main="": entrypoint package -verbose=false: log verbose -w=false: write result to (source) file instead of stdout

== DESCRIPTION

tsgen is a toolbox for type switch statements in Go. Basically it does code generation to help coding with type switches. Currently it supports three functions: expand, sort and scaffold. expand generates new case clause from template clause with type placeholders, achieving type generic codes. scaffold fills type switches with stub case clauses. sort sorts case clauses in type switches.

In any mode -w option will rewrite the file itself, otherwise prints out to stdout.

== TEMPLATE EXPANSION: USING TEMPLATE VARIABLES

[source,go]

// example.go type T interface{} // treated as a type variable

func onGenericStringMap(m interface{}) {
switch m := m.(type) {
case map[string]T:
var x T
...
}
}

And in somewhere:

[source,go]

// main.go
func main() {
onGenericStringMap(map[string]bool{})
onGenericStringMap(map[string]io.Reader{})
}

And run:

tsgen example.go

Then you will get type switch clauses whose type variables are replaced with concrete types:

[source,go]

func onGenericStringMap(m interface{}) []string {
switch m := m.(type) {
case map[string]bool:
var x bool
...
case map[string]io.Reader:
var x io.Reader
...
case map[string]T:
var x T
...
}
}

== TEMPLATE EXPANSION: DESCRIPTION

tsgen expand rewrites type switch statements which has template case clauses, which are case clauses with type variables in their case expression (e.g. case map[string]T: or case chan S1:). tsgen analyzes the source code and detects the actual argument types (e.g. map[string]io.Reader or chan bool), then generates new case clauses with concrete types based on the templates and adds them to the parent type switch statement.

Types with names of uppercase letters and numbers are considered as type variables.

== USAGE WITH go generate

Add lines below to expand type switches with go generate:

[source,go]

//go:generate tsgen -w expand $GOFILE
//go:generate goimports -w $GOFILE

For a complete example, consult the _example directory.

== AUTHOR

motemen [email protected]