On Thu, 14 Apr 2022, 09:50 'Sebastien Binet' via golang-nuts, < golang-nuts@googlegroups.com> wrote:
> hi there, > > I am playing a bit with generics. > I am trying to implement a parametrized "Read" function that unmarshals > bytes into some type value that implements an interface: > > type T1 struct { > v string > } > > func (t *T1) UnmarshalBinary(p []byte) error { > t.v = string(p) > return nil > } > > type Unmarshaler interface { > UnmarshalBinary(p []byte) error > } > > func f1[T Unmarshaler](p []byte) (T, error) { > var t T > err := t.UnmarshalBinary(p) > return t, err > } > > func main() { > p := []byte("hello") > t1, err := f1[T1](p) > if err != nil { > log.Panic(err) > } > > log.Printf("t1: %+v", t1) > } > > my naive attempt failed like so: > > ./prog.go:26:16: T1 does not implement Unmarshaler (UnmarshalBinary method > has pointer receiver) > > it's only when I rewrite my f1 function like so that it "works": > > func f2[T any](p []byte) (t T, err error) { > switch t := any(&t).(type) { > case Unmarshaler: > err = t.UnmarshalBinary(p) > default: > panic("boo") > } > return t, err > } > > but it doesn't take advantage of the nice type constraints Go's generics > provide. > > of course, replacing: > t1, err := f1[T1](p) > > with: > t1, err := f1[*T1](p) > compiles. but fails at runtime. > > what am I missing? > how do I convey the constraint "unmarshaling usually imply passing a > pointer to some value" ? > This is a classic use case for structural type constraints: https://go.dev/play/p/-stEjeeqQD0 > > -s > > -- > 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/CJ9U1G7RBSM9.I0L5BA20IVD1%40clrinfopc42 > . > -- 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/CAJhgacg4DpiVK_%3Dq5EswxwCPmF%2BTOoZ38d9C50%3DkdWkYR-AN%3DQ%40mail.gmail.com.