Expands type switches with type variables to achieve generic functions in Golang
= 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
// example.go type T interface{} // treated as a type variable
And in somewhere:
And run:
tsgen example.go
Then you will get type switch clauses whose type variables are replaced with concrete types:
== 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
:
For a complete example, consult the _example
directory.
== AUTHOR
motemen [email protected]