On Wed, Jun 17, 2020 at 12:09 AM Sebastien Binet <d...@sbinet.org> wrote: > > I was playing a bit w/ pointer methods[1] to see how this could be applied to > a pet peeve of mine: ensuring at compile-time that, e.g., json.Decoder.Decode > takes a pointer to a value: > > https://go2goplay.golang.org/p/J2Lr5QrkKTj > > this works: > > func Decode(type *T)(ptr *T) error { > return json.NewDecoder(new(bytes.Buffer)).Decode(ptr) > } > > func main() { > var v int > Decode(int)(&v) > } > > as well as this: > > type Decoder(type *T) struct{} > > func (dec *Decoder(T)) Decode(ptr *T) error { > // ... > return nil > } > > func main() { > var v int > dec := Decoder(int){} > dec.Decode(&v) > } > > but I was initially caught off guard trying to write the method on Decoder > like so: > > // ERROR: receiver type parameter *T must be an identifier > func (dec *Decoder(*T)) Decode(ptr *T) error { > return nil > } > > (notice the extra '*' in Decoder(*T)) > > perhaps something to mention in the document? > > -s > > [1]: > https://go.googlesource.com/proposal/+/refs/heads/master/design/go2draft-type-parameters.md#pointer-methods
Using a pointer method, as in "type *T", does not mean that the type argument must be a pointer. If you write "(type *T C)", it means that, given a type argument A, the type *A must implement the constraint C. There is actually no reason to ever write "(type *T)" with no constraint. That means that, given a type argument A, the type *A must implement the empty constraint, which it does, because all types implement the empty constraint. Pointer methods do seem to be confusing. I think they have a clear use, but it may be that they are too confusing for that use. Ian -- 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/CAOyqgcU5Mwg54%3DnRWBQ3kDaeRJV8KZ1DorZHsbLnvNGZo84ttA%40mail.gmail.com.