3 ms·
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
by dastx 6y ago
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.
- lma21 6y agowould you have a sample code? sounds interesting
- dastx 6y agoExample 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.
- itake 6y agoCode 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.
- tsimionescu 6y agoAnd install stringer in every dev env, and debug all the boilerplate anyway when things go wrong. Code generation is always the last resort.
- dastx 6y agoI'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.