Home  >  Article  >  Backend Development  >  How to Pass Variable Parameters to Sprintf in Go with Slices of Strings?

How to Pass Variable Parameters to Sprintf in Go with Slices of Strings?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-29 00:40:02180browse

How to Pass Variable Parameters to Sprintf in Go with Slices of Strings?

Passing Variable Parameters to Sprintf in Go

In Go, the Sprintf function expects its variable arguments to be of type []interface{}. This can be a limitation when working with slices of other types, such as []string.

Consider the following code, which attempts to pass a slice of strings to Sprintf:

<code class="go">s := []string{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])</code>

Running this code will result in the following error:

cannot use v (type []string) as type []interface {} in argument to fmt.Printf

To resolve this error, the slice must be converted to type []interface{}. This can be done manually, as shown below:

<code class="go">ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}</code>

Alternatively, a slice of strings can be declared as []interface{} from the start:

<code class="go">is := []interface{}{"a", "b", "c"}</code>

With the slice converted to the correct type, Sprintf can now be used to format the variable arguments:

<code class="go">fmt.Printf("%5s %4s %3s\n", is[1], is[2], is[3])</code>

Output:

b    c   d

By converting the slice of strings to []interface{}, it becomes possible to pass multiple arguments to Sprintf conveniently.

The above is the detailed content of How to Pass Variable Parameters to Sprintf in Go with Slices of Strings?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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