On Sun, 25 Nov 2018 at 18:25, Ian Denhardt <i...@zenhack.net> wrote: > Quoting roger peppe (2018-11-25 12:01:08) > > On Sun, 25 Nov 2018 at 16:54, 'Axel Wagner' via golang-nuts > > <[1]golang-nuts@googlegroups.com> wrote: > > > > I'd suggest simply > > func (b *Binlog) writeArgumentToOutput(writer writer, arg uint64) > error > > { /* do the writing */ } > > and doing the actual conversions at the call-site. It's type-safe, > > shorter, faster and more idiomatic - with the tiny downside of a > > `uint64()` here and there. > > Alternatively, use reflect as it's intended to - something like > > func� writeArgumentToOutput(writer writer, arg interface{}) error { > > � � rv := reflect.ValueOf(arg) > > � � var v uint64 > > � � if k := rv.Kind(); k >= reflect.Int && k < reflect.Uint { > > > > I know constants are protected by the Go compatibility guarantee, > doing > > range comparisons on reflect.Kind constants seems a bit dubious to me. > > Without going to the definitions, it's not clear to the reader which > > exact kinds are included here. I'd suggest enumerating all the > expected > > kinds directly in a switch statement (the compiler may well optimize > to > > a range comparison for that anyway). > > I agree; had to stare at this a bit. Something like: > > switch rv.Kind() { > case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, > reflect.Int64: > v = uint64(rv.Int()) > case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, > reflect.Uint64: > v = rv.Uint() > default: > return fmt.Errorf("Unsupported type: %T\n", reflect.TypeOf(arg)) > } >
Yes - I linked to some very similar play.golang.org code in my first reply in this thread. I wonder whether reflect.Type should have "CanInt", and "CanUint" methods that can be called to determine whether it's OK to call Value.Int and Value.Uint respectively, without needing to explicitly enumerate all the int-like types. Only slightly more verbose, but much easier to understand. But ultimate > Axel's first instinct is I think the right one -- just do the cast at > the call site. > Agreed, but this might not be possible if the value has come from within some other type using reflect. > -- > 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. > For more options, visit https://groups.google.com/d/optout. > -- 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. For more options, visit https://groups.google.com/d/optout.