Go: proposal: allow copy builtin function to copy a slice of undirected channels to a slice of directed channels

Created on 6 Oct 2020  路  4Comments  路  Source: golang/go

Hello,

The only one found solution to #41695 (and #40010 by extension) which is actually the only one safe is just to allow the builtin copy function from a slice of undirected channels to a slice of directed channels.

package main

func main() {
    src := []chan int{make(chan int)}

    var dest []<-chan int
    _ = copy(dest, src)
}

We got the following error: arguments to copy have different element types: []<-chan int and []chan int.

Today, the only one solution is :

package main

func myChanIntCopy(dest []<-chan int, src []chan int) int {
    elemCopied := 0
    for i, c := range src {
        if cap(dest) <= i {
            dest = append(dest, c)
        } else {
            dest[i] = c
        }
        lenCopied = i + 1
    }
    return elemCopied
}

func main() {
    var dest []<-chan int

    src := []chan int{make(chan int)}
    _ = myChanIntCopy(dest, src)
}

_The idea came from @bcmills: https://github.com/golang/go/issues/41695#issuecomment-703641845_

Proposal

Most helpful comment

I think this is effectively a dup of #15209.

All 4 comments

This proposal should be more general and relaxed to the cases in which implicit conversions are allowed from source element type to destination element type. For example:

package main

type T *int

func main() {
    var a [100]T
    var b = make([]*int, len(a))
    copy(b, a[:]) // error: arguments to copy have different element types: []*int and []T
}

Same problem for append:

package main

type T *int

func main() {
    var a [2]T
    var b = make([]*int, len(a))
    b = append(b[:0], a[0], a[1]) // ok
    b = append(b[:0], a[:]...) // error: cannot use a[:] (type []T) as type []*int in append
}

I think this is effectively a dup of #15209.

I think this is effectively a dup of #15209.

This is a dup. I did check for this and don't successfully found it (to many issues lol). It can be closed so.

Was this page helpful?
0 / 5 - 0 ratings