Home > Article > Backend Development > How to Pass a String Slice to an Empty Interface Variadic Parameter in Go?
Pass a String Slice to an Empty Interface Variadic Parameter
Question:
The gosqlite package provides a method with a variadic parameter of type empty interface. However, when attempting to pass a slice of strings as the parameter, the compiler generates an error. Is there a way to do this, or a more efficient method for converting the slice to an empty interface?
Answer:
It's not possible to directly pass a []string to a ...interface{} parameter. The conversion requires linear time, which can introduce a significant hidden cost.
Instead, you can create a separate function that takes a []string and returns the corresponding []interface{}. Alternatively, you can use reflection, although this comes with a runtime overhead. Here's an example using reflection:
<code class="go">valuesVal := reflect.ValueOf(values) for i := range values2 { values2[i] = valuesVal.Index(i).Interface() } </code>
The above is the detailed content of How to Pass a String Slice to an Empty Interface Variadic Parameter in Go?. For more information, please follow other related articles on the PHP Chinese website!