Generics Ordered constraint - both for primitives and custom structs?

Is there any way to create a generic type T that works both of primitive types and custom structs ?

Namely func f[T constraints.Ordered]() will work for any primitive type that supports <,> and ==. Now, I want a type that accepts both primitive types, and custom structs that implement a Less() method for comparisons.

Do I need to write two methods, one for the primitive type, one for customs structs ? Is there any trick that allows me to write the code only once ?

In case you can, not sure, are you planning to do type checking inside the function in order to use the right comparison?

I do not know, looking for ideas. Clearly doing type checking is bad complexity wise, as it adds a little more complexity and a little more extra work.

well, I’d prefer to have 2 different functions:

  • one accepting a constraints.Ordered param
  • one accepting a Lesser interface

This doesn’t answer to your original question (how to create a function that accepts both) but looks more clear to me.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.