The const/slice implementation should be faster as Jan said. Note that there is also a blank function that fails at compile time if items have been added or changed and stringer has not been rerun since. The const/slice implementation allows for that (useful!) check.
Le mardi 18 février 2020 07:42:41 UTC+1, Vincent Blanchon a écrit : > > Hello, > > I was wondering why the stringer command has been implemented that way: > > const _Pill_name = "PlaceboAspirinIbuprofen" > > var _Pill_index = [...]uint8{0, 7, 14, 23} > > 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]] > } > > > > When it could be simpler and faster with a simple enum: > > func (i Pill) String() string { > switch i { > case 0: return "Placebo" > case 1: return "Aspirin" > case 2: return "Ibuprofen" > case 3: return "Paracetamol" > default: return "Pill(" + strconv.FormatInt(int64(i), 10) + ")" > } > } > > > After running a benchmark with a higher number of values (20), the enum is > always faster. I also was surprised to see the binary is not bigger (maybe > it will be with more values). > > Does someone know what advantages the current design brings? > -- 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 golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/bff0982a-a80b-4153-b316-1576f65700c5%40googlegroups.com.