How to Pass a String Slice to an Empty Interface Variadic Parameter in Go?

Patricia Arquette
Release: 2024-11-06 12:10:02
Original
200 people have browsed it

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>
Copy after login

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!

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