Hi everyone! I wanted to ask about the error in the title: "cannot use a 
type parameter as RHS in type declaration".

My use case: I am implementing range queries on a single dimension, and use 
a common type, e.g. int64. There is a method that I have to implement that 
is Contains(v int64) bool. For space efficiency, if for any reason a range 
of int64 numbers contains a single value, then I make let's say two 
implementations, one for 32 and one for 64 bytes. If the only value in the 
range can be represented with an int32, then I use it. Please, bear in mind 
that this is a simplification of my use case, but it correctly captures my 
concern.

My attempt:

type oneValue[T interface{int32 | int64}] T
func (x oneValue[T]) Contains(v int64) bool { return v == int64(x) }

As that causes the aformentioned error, my current approach is:

type oneValue[T interface{int32 | int64}] [1]T
func (x oneValue[T]) Contains(v int64) bool { return v == int64(x[0]) }

Of course, this can also be expressed as:

type oneValue[T interface{int32 | int64}] struct {
    Value T
}
func (x oneValue[T]) Contains(v int64) bool { return v == int64(x.Value) }

I found that the two approaches are functionally equivalent for the most 
part (maybe I'm missing something). Some key points:
1. There doesn't seem to be any struct alignment, space use, or performance 
difference in neither of the three.
2. For generic versions, in general, a custom (un)marshaler may be needed 
(a dumb one  pointing the (un)marshaler is enough). For JSON encoding, for 
example, the first generic version creates a JSON Array with a single 
element; and the second a JSON Object with a single `Value` member.

Considering the three approaches: (A) non-generic; (B) generic with struct; 
(C) generic with an array of one element:
1. Can you explain why this error happens ? what problems it would create 
that was allowed? Any oneliner pointing to docs or just "look for x" is 
great! I may be missing something too obvious.
2. Are there other atlternatives you can think of, even dumb ones, and how 
would they compare to the three above?
3. Are there other differences or concerns you can think of, that were not 
addressed above?

Thank you!

-- 
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/c34e29b7-242b-41f1-8ca4-4cca574fec7bn%40googlegroups.com.

Reply via email to