mapgen
mapgen
is a Go code generation tool for creating utility functions and maps for constants defined in a specific type. It dynamically generates helper functions to simplify working with constants, such as converting them to strings, extracting keys, and validating values.
Installation
To install mapgen
, use the following command:
go install github.com/c9s/mapgen@latest
This will install the mapgen
binary to your $GOPATH/bin
directory.
Usage
The mapgen
tool takes a type name and generates utility functions and maps for constants of that type.
Command-Line Flags
Flag |
Description |
-type |
The name of the type for which constants are to be processed (required). |
-output |
Output file name. Defaults to <type>map.go . |
-stdout |
Print the generated code to standard output instead of writing to a file. |
Examples
Generate Code for PrivateChannel
Suppose you have a type PrivateChannel
with several constants:
type PrivateChannel string
const (
PrivateChannelOrder PrivateChannel = "order"
PrivateChannelTrade PrivateChannel = "trade"
// @group Margin
PrivateChannelMarginOrder PrivateChannel = "margin_order"
)
Run mapgen
as follows:
mapgen -type PrivateChannel
This will generate a file privatechannelmap.go
with the following content:
// Code generated by mapgen; DO NOT EDIT.
package main
var AllPrivateChannel = map[PrivateChannel]struct{}{
PrivateChannelOrder: {},
PrivateChannelTrade: {},
PrivateChannelMarginOrder: {},
}
var AllMarginPrivateChannel = map[PrivateChannel]struct{}{
PrivateChannelMarginOrder: {},
}
// PrivateChannelStrings converts a slice of PrivateChannel to a slice of string
func PrivateChannelStrings(slice []PrivateChannel) (out []string) {
for _, el := range slice {
out = append(out, string(el))
}
return out
}
// PrivateChannelKeys converts a map of PrivateChannel to a slice of PrivateChannel
func PrivateChannelKeys(values map[PrivateChannel]struct{}) (slice []PrivateChannel) {
for k := range values {
slice = append(slice, k)
}
return slice
}
// ValidatePrivateChannel validates a value of type PrivateChannel
func ValidatePrivateChannel(ch PrivateChannel) bool {
_, ok := AllPrivateChannel[ch]
return ok
}
Use -stdout
to Print Generated Code
To print the generated code to the terminal instead of writing it to a file, use the -stdout
flag:
mapgen -type PrivateChannel -stdout
Custom Output File
To specify a custom output file name, use the -output
flag:
mapgen -type PrivateChannel -output custom_file.go
Features
License
mapgen
is released under the MIT License. See LICENSE for more details.