typestringer
This program can be used to generate customizable code based on Go type names.
One example would be the generation of String() functions to fulfill the
Stringer interface.
Usage
$ typestringer -help
Several options exist for customizing the generated code. -include and
-ignore may be used to define regular expressions for matching or not matching
specific types. Diagnostic output is written to standard error and generated
code by default to files located in the package paths. -stdout may be used to
redirect the generated code to standard output.
As usual, typestringer may also be executed with go generate by including a
comment such as the following somewhere in your code:
//go:generate typestringer
Installing
Builds for many platforms can be found
here. You may also use the Go
toolchain:
$ go install github.com/susji/typestringer@latest
Examples
The examples below use the typestringer code.
Basic
The type-specific format string is expanded with the type name passed two times
so escaping other formatting directives must be done with %%:
$ typestringer \
-stdout \
-preamble 'import fmt' \
-fmt 'func (t %s) String() string { return fmt.Sprintf("%s=%%v", t) }'
The generated code looks like this:
// Automatically generated by typestringer with the following parameters:
// -stdout
// -preamble
// import fmt
// -fmt
// func (t %s) String() string { return fmt.Sprintf("%s=%%v", t) }
package main
import fmt
func (t stringsvar) String() string { return fmt.Sprintf("stringsvar=%v", t) }%
Chaining
If specific types should be treated differently and one generated file is
desired, something like the following may be done:
$ { typestringer \
-stdout \
-preamble 'import fmt' \
-include '^FIRST$' \
-fmt 'func (t %s) String() string { return fmt.Sprintf("%s=%%v", t) }'$'\n' \
./generator/testdata/two;
typestringer \
-stdout \
-no-package \
-include '^SECOND$' \
-fmt 'func (t %s) String() string { return "%s" }'$'\n' \
./generator/testdata/two;
} 2>/dev/null
The generated code looks like this:
// Automatically generated by typestringer with the following parameters:
// -stdout
// -preamble
// import fmt
// -include
// ^FIRST$
// -fmt
// func (t %s) String() string { return fmt.Sprintf("%s=%%v", t) }
// ./generator/testdata/two
package two
import fmt
func (t FIRST) String() string { return fmt.Sprintf("FIRST=%v", t) }
// Automatically generated by typestringer with the following parameters:
// -stdout
// -no-package
// -include
// ^SECOND$
// -fmt
// func (t %s) String() string { return "%s" }
// ./generator/testdata/two
func (t SECOND) String() string { return "SECOND" }