Home > Backend Development > Golang > How to Pass a Slice of Slices as Unpacked Arguments to a Variadic Function in Go?

How to Pass a Slice of Slices as Unpacked Arguments to a Variadic Function in Go?

Barbara Streisand
Release: 2024-10-28 08:20:29
Original
669 people have browsed it

How to Pass a Slice of Slices as Unpacked Arguments to a Variadic Function in Go?

Unpacking Slice of Slices as Variadic Arguments

Problem:
When attempting to pass a slice of slices as unpacked arguments to a variadic function, a compilation error occurs. The error indicates an inability to assign the source slice type to the destination variadic parameter type.

Explanation:
According to the Go specification, a function with variadic parameters of type ...T expects a single slice of type []T as an argument. However, in the case of a slice of slices, [][]T, this condition cannot be met.

Solution:
To resolve this issue, a new slice of the required type []T must be created and populated with the desired values. This new slice can then be passed unpacked using the ellipsis operator (...).

Example:

<code class="go">package main

import (
    "fmt"
)

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

func main() {
    sliceOfSlices := [][]int{
        []int{1, 2},
        []int{101, 102},
    }

    // Create a new slice of type []interface{}
    sliceOfInterfaces := []interface{}{}
    for _, v := range sliceOfSlices {
        sliceOfInterfaces = append(sliceOfInterfaces, v)
    }

    unpack(sliceOfInterfaces...) // Pass unpacked values
}</code>
Copy after login

Output:

2
Copy after login

In this example, the unpack() function is called with the unpacked elements of the sliceOfSlices as arguments. The len() function is used to demonstrate the number of arguments passed, which indicates that both elements of the nested slice are unpacked.

The above is the detailed content of How to Pass a Slice of Slices as Unpacked Arguments to a Variadic Function in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template