Re:Leveraging the Go Type System
by dastx on Tuesday February 09, 2021 @12:29PM
(#26080198)
That boiler plate usually can be generated for you. See Go's stringer which does all the magic for you. All you have to do is define the type and constants, and a go generate directive.
[ Parent
| on HN ]
Code generators don't solve the problem of the language being too verbose/boiler plate. Instead of expressing a concept in a simple fashion, you have to generate 100s of lines of code that needs to be maintained across versions of golang and your data model.
Re:Leveraging the Go Type System
by tsimionescu on Tuesday February 09, 2021 @04:09PM
(#26082411)
And install stringer in every dev env, and debug all the boilerplate anyway when things go wrong.
Code generation is always the last resort.
I'm not saying it's the solution. I'm just pointing what is idiomatic go. Certainly there are arguments for and against code generation.
Where I work we are a go house, and the number of tools I've seen in our pre-commit configurations and in our development environment setup scripts is pretty intense. So is the number of questions around said tooling. There's a lot more friction than I'd expect. I can't even use lack of experience as an excuse for these questions because they're really talented people. Some of them have worked on the product for years, and have literally moulded the product's tooling into what it is today.
would you have a sample code? sounds interesting
Example from the docs:
// pill.go
package painkiller
//go:generate stringer -type=Pill
type Pill int
const (
Placebo Pill = iota
Aspirin
Ibuprofen
Paracetamol
Acetaminophen = Paracetamol
)
Then running `go generate` will yield: $ cat pill_string.go
// Code generated by "stringer -type=Pill"; DO NOT EDIT.
package painkiller
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Placebo-0]
_ = x[Aspirin-1]
_ = x[Ibuprofen-2]
_ = x[Paracetamol-3]
}
const _Pill_name = "PlaceboAspirinIbuprofenParacetamol"
var _Pill_index = [...]uint8{0, 7, 14, 23, 34}
func (i Pill) String() string {
if i < 0 || i >= Pill(len(_Pill_index)-1) {
return "Pill(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Pill_name[_Pill_index[i]:_Pill_index[i+1]]
}
Note: indentation is messing up because of Hacker News, so ignore the indentation.