stringerParser

command
v0.0.0-...-3999d51 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 15, 2020 License: BSD-3-Clause Imports: 15 Imported by: 0

Documentation

Overview

Stringer is a tool to automate the creation of methods that satisfy the fmt.Stringer interface. Given the name of a (signed or unsigned) integer type T that has constants defined, stringer will create a new self-contained Go source file implementing

func (t T) String() string

The file is created in the same package and directory as the package that defines T. It has helpful defaults designed for use with go generate.

Please note: this is a modified version of the original tool. Please, see the Footnote for more information.

Stringer works best with constants that are consecutive values such as created using iota, but creates good code regardless. In the future it might also provide custom support for constant sets that are bit patterns.

For example, given this snippet,

package painkiller

type Pill int

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

running this command

stringer -type=Pill

in the same directory will create the file pill_string.go, in package painkiller, containing a definition of

func (Pill) String() string

That method will translate the value of a Pill constant to the string representation of the respective constant name, so that the call fmt.Print(painkiller.Aspirin) will print the string "Aspirin".

Typically this process would be run using go generate, like this:

//go:generate stringer -type=Pill

If multiple constants have the same value, the lexically first matching name will be used (in the example, Acetaminophen will print as "Paracetamol").

With no arguments, it processes the package in the current directory. Otherwise, the arguments must name a single directory holding a Go package or a set of Go source files that represent a single Go package.

The -type flag accepts a comma-separated list of types so a single run can generate methods for multiple types. The default output file is t_string.go, where t is the lower-cased name of the first type listed. It can be overridden with the -output flag.

The -linecomment flag tells stringer to generate the text of any line comment, trimmed of leading spaces, instead of the constant name. For instance, if the constants above had a Pill prefix, one could write

PillAspirin // Aspirin

to suppress it in the output.

Footnote:

Modified by Diego Augusto Molina Report bugs to <diegoaugustomolina@gmail.com>

Most of the above documentation has been preserved verbatim, but bear in that this tool is named 'stringerParser' to avoid collision with the original.

This modified version includes a 'Parse' method for reversing the String method. This allows to perform validations and if a string cannot be parsed into a value then the zero value is returned. The Parse method has the form:

func (t *T) Parse(string) T

The method changes the value so you can write something like:

if new(T).Parse(someInputString) == T(0) {
    return fmt.Errorf("Invalid string value")
}

Or something simpler like:

myStruct.EnumeratedField := new(T).Parse(someInputString)

Or even:

var myT T
myT.Parse(someInputString)

And also may prove valuable if multiple T values need to be parsed (note

 //go:generate stringerParser -type=T
 package main

 type T uint8

 const (
     TInvalid T = iota // Reserved for internal use. This is recommended

     TValue1
     TValue2
     //...
 )

 func main() {
     var myT T
     stringsToValidate = []string{
			"TValue1",
			"TInvalid",
			"This will also be parsed as TInvalid",
		}

     for _, str := range stringsToValidate {
         if myT.Parse(str) == TInvalid {
             // Handle invalid value
         }
     }
 }

And it is also trivial to implement a custom validation function for T:

	import validator "gopkg.in/go-playground/validator.v10"

 func validateT(fl validator.FieldLevel) bool {
		return new(T).Parse(fl.Field().String()) != T(0)
	}

TODO: * Support for duplicate string values * Support for sparse enum values * Add tests

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL