You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
stringer is great, but in my opinion it's limited to the characters that you can use as a name in a Go program.
To illustrate, imagine constants that define operators in a language. You can't define the add operator, +, with its own string as the name. You have to use a descriptive name like Add or ADD, that consists of characters that can form an identifier in a Go program.
I have a similar situation in a package of mine. I wanted these token constants to implement fmt.Stringer, so I first set up a String() method that would just switch on the value and return a string.
This had a couple of major issues, however. For one, it was inefficient. The way stringer lays out the data in a single string and uses indices is much faster. For another, it was cumbersome to maintain that boilerplate code that was overly verbose.
and // &
andAnd // &&
orOr // ||
or // |
orAnd // |&
And I modified stringer (CL incoming) to add a flag to use an inline comment's text as the string value, rather than the name of the identifier itself. This of course falls back to the identifier name if there is no inline comment.
stringer
is great, but in my opinion it's limited to the characters that you can use as a name in a Go program.To illustrate, imagine constants that define operators in a language. You can't define the add operator,
+
, with its own string as the name. You have to use a descriptive name likeAdd
orADD
, that consists of characters that can form an identifier in a Go program.This is what
go/ast
does: https://golang.org/src/go/token/token.go#L35I have a similar situation in a package of mine. I wanted these token constants to implement
fmt.Stringer
, so I first set up aString()
method that would just switch on the value and return a string.This had a couple of major issues, however. For one, it was inefficient. The way
stringer
lays out the data in a single string and uses indices is much faster. For another, it was cumbersome to maintain that boilerplate code that was overly verbose.So I laid out these values with inline comments containing only their string representation: https://github.com/mvdan/sh/blob/master/syntax/tokens.go
And I modified
stringer
(CL incoming) to add a flag to use an inline comment's text as the string value, rather than the name of the identifier itself. This of course falls back to the identifier name if there is no inline comment.You can see the result in this file: https://github.com/mvdan/sh/blob/master/syntax/token_string.go
I realise this behaviour may not be desired in many situations, so that's why I think it's best to hide it behind a flag.
As said, CL incoming - the patch is rather simple.
The text was updated successfully, but these errors were encountered: