Generics and constraints question

188 views
Skip to first unread message

Brian Candler

unread,
Jan 5, 2021, 12:31:59 PM1/5/21
to golang-nuts
Question: how to make a generic function which takes a type T where the constraint is "*T satisfies a given interface"?

func (m *MyMap[KT, VT]) init() {
        m.data = make(map[KT]VT)
}

type Initializer interface {
init()
}

func mynew[T Initializer]() *T {
t := new(T)
t.init()
return t
}

/* or:
func mynew[T Initializer]() *T {
var t T
t.init()
return &t
}
*/

func main() {
m := mynew[MyMap[string, int]]()
}

gives: 

type checking failed for main prog.go2:34:13: MyMap[string, int] does not satisfy Initializer: wrong method signature
        got func (*MyMap[KT, VT]).init()
        want func (Initializer).init()



roger peppe

unread,
Jan 5, 2021, 3:27:57 PM1/5/21
to Brian Candler, golang-nuts
You can do this with type-list interfaces: https://go2goplay.golang.org/p/wfHnVHOMcyK

This is one of the harder parts of the proposal to understand IMHO, but perhaps it will become easier with familiarity.

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/13dcb9b5-da98-49b9-abf7-05c95b1d4ebdn%40googlegroups.com.

Ian Lance Taylor

unread,
Jan 5, 2021, 3:52:44 PM1/5/21
to roger peppe, Brian Candler, golang-nuts, Robert Griesemer
This definitely needs a better error message.

Ian
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJhgacgvJ%3D6eoH_Uh%2B69SdDk3C0nMep35SUhpv4QnsgAQw3kcA%40mail.gmail.com.

Brian Candler

unread,
Jan 5, 2021, 4:54:17 PM1/5/21
to golang-nuts
On Tuesday, 5 January 2021 at 20:27:57 UTC rog wrote:
You can do this with type-list interfaces: https://go2goplay.golang.org/p/wfHnVHOMcyK

This is one of the harder parts of the proposal to understand IMHO, but perhaps it will become easier with familiarity.

Thank you! 
Reply all
Reply to author
Forward
0 new messages