Looking for a Go way to extract all consts from a ...
# dev
a
Looking for a Go way to extract all consts from a package. This can be at runtime (reflect during startup) or at build time (go generate ...magic...). My intended usage is to get a slice containing the names of all Actions from package permissions. They are all consts that end in "Action". For motivation: in C I would just list the actions in a separate source file wrapped in a macro ACTION, then include it twice with different definitions of ACTION. It would take 4 lines and they would be readable. SURELY GO CAN DO BETTER!
👀 1
@Barak Amar would something like this work?
o
🤢 1
👓 1
a
Looking...
Yeah, it's halfway down the list of packages for understanding Golang types.
b
Using code parse ^
Had to set a type so it will be easy to pull the relevant ones. Based on other code I found.
But I would consider to just have a slice that contains all of the values and not to reflect if possible
or validation func that will include a big switch case with true for all the right ones
Our code today just validate format - but possible values
a
Yeah. it's not reflection 🙂 Thing is: how do I get a FileSet after the program has already been built? Anyway, I reckon I'll
go generate
and put all the constants between two comment lines. Can I
//go:generate go run ./cmd/tools/extract_xyzzy
?
b
The above code needs the source like in go generate. So I think we both use the same technic.
a
Ended up using your stuff in a
go generate
command, @Barak Amar. Awesome, thanks! (But I still miss my preprocessor).
🤘 1
Works :-) Happy for reviews...