Go: cmd/go2go: adding strings together is not defined

Created on 17 Jun 2020  路  5Comments  路  Source: golang/go

I've been experimenting a bit with generics at https://go2goplay.golang.org/ and I think I found a bug.

What did you do?

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
}

What did you expect to see?

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
}

What did you see instead?

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.

NeedsFix

Most helpful comment

This is now fixed in dev.go2go. Will be fixed in the playground as soon as it's updated.

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings