This seems like such an obvious idea, but I was unable to find prior discussion 
about it — it is probably at least implicit in various generics alternative 
proposals etc, but anyway, seems like it might be worth at least saying why 
this wouldn’t be useful to provide in standard packages?

Idea: If there were standard packages that provide basic interfaces akin to 
fmt.Stringer, for ints and floats (and all other basic types), with 
bidirectional conversion functions, might that go a long way toward filling 
some of the generics gaps?

e.g.: https://play.golang.org/p/v1S1IMigoy6

// in package ints

type Inter interface {
        Int() int64
        FromInt(val int64)
}

func Max(a, b Inter) int64 {
        if a.Int() > b.Int() {
                return a.Int()
        }
        return b.Int()
}

so you could write ints.Max(a,b) for anything supporting the Inter interface..  
Obviously a Less method would be avail, and could be used for a fully generic 
sort on slices where you check if the slice element type supports the interface 
(including Floater and Stringer), and it falls back on a big reflect.Kind 
switch in the worst case.  I just wrote this and it seems ugly but useful when 
you really don’t know what you’ve got, and having the interface allows you to 
use things like Time values etc, and is probably faster than fully 
reflect-based.

A similar Floater interface could be defined, maybe in math, and an entire 
generic version of the math library could be implemented as wrappers using the 
Floater interface — obviously a bit of runtime cost using the interface methods 
but seems like it would save a lot of casting and for non-performance-critical 
cases would probably be worth the cleaner code.

If this was all defined as a standard package, then basically every type with 
relevant int, float, etc semantics could be expected to have the relevant 
interface methods, just like virtually everything has a Stringer interface, and 
you could very easily deal with just about any relevant type by defining the 
relevant interface-based methods..

So anyway, what is the fatal flaw with this idea that I’m not seeing?

- Randy

-- 
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.

Reply via email to