Skip to content

Generics: cannot union types with behavioral interfaces #49054

@extemporalgenome

Description

@extemporalgenome

What version of Go are you using (go version)?

$ go version
go version devel go1.18-eba0e866fa Mon Oct 18 22:56:07 2021 +0000 linux/amd64

Does this issue reproduce with the latest release?

N/A: tip

What operating system and processor architecture are you using (go env)?

go env Output
$ go env
GO111MODULE=""
GOARCH="amd64"
GOBIN="/home/kevin/usr/bin"
GOCACHE="/home/kevin/.cache/go-build"
GOENV="/home/kevin/.config/go/env"
GOEXE=""
GOEXPERIMENT=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOINSECURE=""
GOMODCACHE="/home/kevin/go/pkg/mod"
GONOPROXY=""
GONOSUMDB=""
GOOS="linux"
GOPATH="/home/kevin/go"
GOPRIVATE=""
GOPROXY="https://proxy.golang.org,direct"
GOROOT="/home/kevin/goroot"
GOSUMDB="sum.golang.org"
GOTMPDIR=""
GOTOOLDIR="/home/kevin/goroot/pkg/tool/linux_amd64"
GOVCS=""
GOVERSION="devel go1.18-eba0e866fa Mon Oct 18 22:56:07 2021 +0000"
GCCGO="gccgo"
GOAMD64="v1"
AR="ar"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD="/home/kevin/src/sandbox/go2/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build3965098965=/tmp/go-build -gno-record-gcc-switches"

What did you do?

I attempted to make use of the Stringish example from the proposal:

package main

import (
  "fmt"
  "strconv"
)

type Stringish interface {
	string | fmt.Stringer
}

func ToString[T Stringish](v T) string {
  switch x := (interface{})(v).(type) {
  case string:
    return x

  case fmt.Stringer:
    return x.String()
  }

  panic("impossible")
}

func PrintSlice[T Stringish](lst []T) {
  for _, v := range lst {
    fmt.Println(ToString(v))
  }
}

type Int int

func (i Int) String() string {
  return strconv.Itoa(int(i))
}

func main() {
  PrintSlice([]Int{1, 2, 3})
  PrintSlice([]string{"x", "y", "z"})
}

What did you expect to see?

1
2
3
x
y
z

What did you see instead?

go run main.go
# command-line-arguments
./main.go:9:11: cannot use fmt.Stringer in union (interface contains methods)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions