I just made a few mods to the stringer tool to generate a function that
converts a string back to the const int type, e.g., for this const int type:
// SignalType provides standard signals -- can extend by starting at iota +
last signal here
type SignalType int64
const (
NilSignal SignalType = iota
SignalChildAdded // data is the added child
SignalChildDeleted // data is deleted child
SignalChildrenDeleted // no data
SignalNodeUpdated // entire node updated
SignalFieldUpdated // a field was updated -- data is name
of field
SignalTypeBaseN // number of base-level signal type
consts -- this is start for any derived ones
)
it generates this function in the stringer output:
func StringToSignalType(s string) (SignalType, error) {
for i := 0; i < len(_SignalType_index)-1; i++ {
if s ==
_SignalType_name[_SignalType_index[i]:_SignalType_index[i+1]] {
return SignalType(i), nil
}
}
return 0, fmt.Errorf("String %v is not a valid option for type
SignalType", s)
}
Seems like this might be of general utility? Is there some other simpler way
of doing this that I’m overlooking? Patch below. Didn’t handle the
multiple-runs and map cases yet..
- Randy
diff --git a/cmd/stringer/stringer.go b/cmd/stringer/stringer.go
index 4b8d1ba4..291051f8 100644
--- a/cmd/stringer/stringer.go
+++ b/cmd/stringer/stringer.go
@@ -132,7 +132,7 @@ func main() {
g.Printf("\n")
g.Printf("package %s", g.pkg.name)
g.Printf("\n")
- g.Printf("import \"strconv\"\n") // Used by all methods.
+ g.Printf("import (\"strconv\"; \"fmt\")\n") // Used by all methods.
// Run generate for each type.
for _, typeName := range types {
@@ -584,6 +584,15 @@ const stringOneRun = `func (i %[1]s) String() string {
}
return _%[1]s_name[_%[1]s_index[i]:_%[1]s_index[i+1]]
}
+
+func StringTo%[1]s(s string) (%[1]s, error) {
+ for i := 0; i < len(_%[1]s_index)-1; i++ {
+ if s == _%[1]s_name[_%[1]s_index[i]:_%[1]s_index[i+1]] {
+ return %[1]s(i), nil
+ }
+ }
+ return 0, fmt.Errorf("String %%v is not a valid option for type %[1]s",
s)
+}
`
// Arguments to format are:
@@ -600,6 +609,15 @@ const stringOneRunWithOffset = `func (i %[1]s) String()
string {
}
return _%[1]s_name[_%[1]s_index[i] : _%[1]s_index[i+1]]
}
+
+func StringTo%[1]s(s string) (%[1]s, error) {
+ for i := 0; i < len(_%[1]s_index)-1; i++ {
+ if s == _%[1]s_name[_%[1]s_index[i]:_%[1]s_index[i+1]] {
+ return %[1]s(i + %[2]s), nil
+ }
+ }
+ return 0, fmt.Errorf("String %%v is not a valid option for type %[1]s",
s)
+}
`
// buildMultipleRuns generates the variables and String method for multiple
runs of contiguous values.
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.