Home > Backend Development > Golang > 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
Release: 2024-10-29 00:40:02
Original
315 people have browsed it

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

Running this code will result in the following error:

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

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

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

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

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

Output:

b    c   d
Copy after login

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!

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