Skip to content

Allow type conversion of slices of same underlying types #29864

Closed
@svenkanna

Description

@svenkanna

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

go version go1.11.2 linux/amd64

Does this issue reproduce with the latest release?

Yes

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

go env Output
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/vss/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/vss/gorepo"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
CGO_CFLAGS="-g -O2"
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-L/usr/lib"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0 -fdebug-prefix-map=/tmp/go-build489605010=/tmp/go-build -gno-record-gcc-switches"

What did you do?

package main

import (
"fmt"
)

type Ref struct {
i int64
}

type ARef Ref

func findRef(refs []Ref, ref Ref) bool {
for _, r := range refs {
if r == ref {
return true
}
}
return false
}

func main() {
ta := []ARef{{0}, {1}}
found := findRef([]Ref(ta), Ref{0})
fmt.Println(found)
}

https://play.golang.org/p/pDZu77EZwEp

What did you expect to see?

The program should be compiled without error

What did you see instead?

prog.go:24:24: cannot convert ta (type []ARef) to type []Ref

Similar issues have been discussed but closed due to age or a valid reason. I have a Ref type which represents a technology ref. To differentiate a ref for each type, I created new type like ARef because I don;t want them to used one for the other. However I need to write several functions like findRef which operate on Ref type. Here one of the suggested way is to create a slice of Ref and copy elements, this is inefficient and not elegant. IMHO, a language should be consistent in different aspects. Allowing conversion of two types having the same underlying type but not allowing conversion of slices of the same types does not seem consistent.

Though I talked about slices of types in this description which I am practically facing right now, the problem can easily generalized by extended it to other complex type like pointers, array of pointers, maps etc.

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