Unpacking slices

I am curious to unpack a slice of slices and send them as arguments to a variational function.

Let's say we have a function with variable parameters:

func unpack(args ...interface{})

If we do not go through the interface slice, it does not matter if we unpack it or not:

slice := []interface{}{1,2,3}
unpack(slice) // works
unpack(slice...) // works

It is difficult if we have a slice of slices. Here the compiler does not allow you to switch to the unpacked version:

sliceOfSlices := [][]interface{}{
    []interface{}{1,2},
    []interface{}{101,102},
}
unpack(sliceOfSlices) // works
unpack(sliceOfSlices...) // compiler error

The error says:

cannot use sliceOfSlices (type [] [] interface {}) as type [] interface {} in the argument for unpacking

I don’t know why this is happening, since we can clearly pass the type []interface{}to the function. How can I call the unzip method with the unpacked contents sliceOfSlicesas arguments?

Example of a playground: https://play.golang.org/p/O3AYba8h4i

+4
1

Spec: ... :

f p ...T, f p []T.

...

[]T, ...T, .... .

: , sliceOfSlices ( [][]interface{}) args ( []interface{}) ( ).

, unpack(slice), unpack() interface{}, slice ( []interface{}) interface{} .

unpack(slice...), slice unpack(); , slice []interface{}, (args ...interface{}).

, unpack(sliceOfSlices), sliceOfSlices interface{} .

unpack(sliceOfSlices...), sliceOfSlices unpack(), sliceOfSlices ( [][]interface{}) , , .

sliceOfSlices unpack() "exploded" - , []interface{}, , ....

:

var sliceOfSlices2 []interface{}
for _, v := range sliceOfSlices {
    sliceOfSlices2 = append(sliceOfSlices2, v)
}

unpack(sliceOfSlices2...)

Go Playground.

unpack() :

func unpack(args ...interface{}) {
    fmt.Println(len(args))
}

( ), :

1
3
1
2

..., ( interface{}), ..., .

Go Playground.

+5

Source: https://habr.com/ru/post/1657041/


All Articles