Home > Backend Development > Golang > How to Pass Variable Parameters to Sprintf in Go with a Slice of Strings?

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

DDD
Release: 2024-11-04 11:40:02
Original
908 people have browsed it

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

Passing Variable Parameters to Sprintf in Go

When working with a large number of parameters, manually passing them to Sprintf can be tedious. Fortunately, there is a way to simplify this process.

Issue:

Attempting to pass a slice of strings ([]string) directly to Sprintf results in an error:

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

Solution:

To resolve this error, declare the slice as a type of []interface{} instead of []string. Sprintf expects an array of interface{} parameters, as seen in its signature:

func Printf(format string, a ...interface{}) (n int, err error)
Copy after login

Example:

s := []interface{}{"a", "b", "c", "d"}
fmt.Printf("%5s %4s %3s\n", s[1], s[2], s[3])

v := s[1:]
fmt.Printf("%5s %4s %3s\n", v...)
Copy after login

Output (Go Playground):

b    c   d
b    c   d
Copy after login

Note:

[]interface{} and []string are not interchangeable. If you have an existing []string, you can manually convert it to []interface{} as follows:

ss := []string{"a", "b", "c"}
is := make([]interface{}, len(ss))
for i, v := range ss {
    is[i] = v
}
Copy after login

The above is the detailed content of How to Pass Variable Parameters to Sprintf in Go with a Slice 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template