I've been experimenting a bit with generics at https://go2goplay.golang.org/ and I think I found a bug.
See: https://go2goplay.golang.org/p/efS6x6s-9NI
I tried concatenating a string:
type IntString interface {
type int, string
}
func Sum(type T IntString)(s []T) (result T) {
for _, v := range s {
result += v // this fails even though it's possible to add strings together
}
return
}
Strings can be added (concatenated) together, so I would expect it to also work when using generics.
Specialized variant of the same function, which does compile:
func SumString(s []string) (result string) {
for _, v := range s {
result += v
}
return
}
It reports the following error:
type checking failed for main
prog.go2:13:3: invalid operation: operator + not defined for result (variable of type T)
Both integers and strings support the + operator so I would expect this to work.
There seems to be some interaction with the int type in the constraint here. This works https://go2goplay.golang.org/p/nYbMg_uv31l:
package main
import "fmt"
func main() {
fmt.Println(Add("Hello", ", world!"))
}
func Add(type T addable)(x, y T) T {
return x + y
}
type addable interface {
type string
}
Hello, world!
But this does not https://go2goplay.golang.org/p/Ksywhb4RF6x:
package main
import "fmt"
func main() {
fmt.Println(Add("Hello", ", world!"))
}
func Add(type T addable)(x, y T) T {
return x + y
}
type addable interface {
type string, int
}
type checking failed for main
prog.go2:10:9: invalid operation: operator + not defined for x (variable of type T)
Yes, this is a bug in the type checker; thanks for reporting.
One of the more complicated things to get right is computing the subset of operations that are valid for all types of a type list. In this case it should have been easy, but obviously there's a bug somewhere.
Change https://golang.org/cl/238359 mentions this issue: [dev.go2go] go/types: use correct predicate when checking binary addition
This is now fixed in dev.go2go. Will be fixed in the playground as soon as it's updated.
FWIW I can confirm that it works in playground now.
Most helpful comment
This is now fixed in dev.go2go. Will be fixed in the playground as soon as it's updated.