How do you write "member" with the proposed generics draft?

93 views
Skip to first unread message

Juliusz Chroboczek

unread,
Aug 4, 2020, 10:32:17 AM8/4/20
to golan...@googlegroups.com
I'd be grateful if people could give me an example to help me understand
the generics draft. Suppose I've got these two functions:

func MemberInt(x int, a []int) bool {
for _, v := range a {
if v == x {
return true
}
}
return false
}

func MemberIP(x net.IP, a []net.IP) bool {
for _, v := range a {
if v.Equal(x) {
return true
}
}
return false
}

I can see how to write a generic "Member" function that takes an extra
equality predicate; but is there a way to write a function that
generalises both functions above without requiring the extra parameter?

Thanks.

Axel Wagner

unread,
Aug 4, 2020, 10:50:56 AM8/4/20
to Juliusz Chroboczek, golang-nuts
No, that's not possible. A generic function can only work with *either* built in operators *or* methods. So, you always need to have two functions: https://go2goplay.golang.org/p/YuzSzDAOEo2


--
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/87v9hytrcn.fsf%40pirx.irif.fr.

Andrei Tudor Călin

unread,
Aug 4, 2020, 11:31:00 AM8/4/20
to Axel Wagner, Juliusz Chroboczek, golang-nuts
I feel like https://go2goplay.golang.org/p/RLn9BXjU1OR is a better compromise than having two functions.



--
Andrei Călin

Axel Wagner

unread,
Aug 4, 2020, 1:39:16 PM8/4/20
to Andrei Tudor Călin, Juliusz Chroboczek, golang-nuts
Prolly. Except OP specifically asked about "not that" :)

Juliusz Chroboczek

unread,
Aug 4, 2020, 1:47:34 PM8/4/20
to Axel Wagner, Andrei Tudor Călin, golang-nuts
Axel Wagner writes:

> I feel like https://go2goplay.golang.org/p/RLn9BXjU1OR is a better
> compromise than having two functions.

> Prolly. Except OP specifically asked about "not that" :)

Agreed on both counts.
Reply all
Reply to author
Forward
0 new messages