#Is a conversion possible between slices of two "identical" structs?

11 messages · Page 1 of 1 (latest)

chrome gate
#

I have a library function that returns a slice of (very simple) structs defined in that library:

// pkg1
type Label struct {
    Name, Value string
}
type Labels []Label
func Get() Labels { ... }

Another unrelated library defines an identical struct and a function that takes a slice of those structs:

// pkg2
type Label struct {
    Name  string
    Value string
}
func Apply(labels []Label) []Label { ... }

As far as I understand, there are conditions under which conversions between identical underlying types are allowed in Go (https://stackoverflow.com/questions/24613271/golang-is-conversion-between-different-struct-types-possible), but those rules don't seem to apply to this specific situation:

// I tried to make every conversion step explicit here
var oldLabels, newLabels []pkg1.Label
var vmOldLabels, vmNewLabels []pkg2.Label
var finalLabels pkg1.Labels
        
oldLabels = pkg1.Get()
vmOldLabels = ([]pkg2.Label)(oldLabels)
vmNewLabels = pkg2.Apply(vmOldLabels)
newLabels = ([]pkg1.Label)(vmNewLabels)
finalLabels = newLabels
path/to/file.go:383:41: cannot convert oldLabels (variable of type []pkg1.Label) to type []pkg2.Label
path/to/file.go:385:32: cannot convert vmNewLabels (variable of type []pkg2.Label) to type []pkg1.Label

Is it somehow possible to convert between those two slice types without copying? If not, how do I do that with the least amount of copying?

mint robin
#

slices in go are slices of a specific type , for any T1, T2 that are different but not type alias a []T1 and []T2 are different

#

you can put []SomeInterface if both have same methods

but otherwise you need to loop to assign

misty beacon
# chrome gate I have a library function that returns a slice of (very simple) structs defined ...

Is it somehow possible to convert between those two slice types without copying?
not without unsafe

this is a recurring topic, https://github.com/golang/go/issues/71183 is the latest iteration

GitHub

Background: It is not uncommon to need to convert a value of slice type []A to type []B, where A and B have the same representation (e.g. string). Unfortunately, one must allocate a copy. Proposal:...

chrome gate
misty beacon
#

yeah

#

I don't see in what circumstances that would be "invalid" but if you want you can go the long way around with unsafe.Slice

chrome gate
mint robin
#

changing or abandoning pkg1 or pkg2 or writing the small adaptation loop seems a lot better than going unsafe route

misty beacon
#

yeah
like I said, I see no reason why that wouldn't be equivalent but I figured it should be mentioned as an option

chrome gate
#

thanks!