Home > Backend Development > Golang > Why does 'foo%!(EXTRA []interface {}=[])' appear when calling a `fmt.Fprintf` wrapper with variadic arguments?

Why does 'foo%!(EXTRA []interface {}=[])' appear when calling a `fmt.Fprintf` wrapper with variadic arguments?

Susan Sarandon
Release: 2024-11-11 02:57:03
Original
192 people have browsed it

Why does

Variadic Function Argument Pass-Through Issue in fmt.Fprintf Wrapper

This article addresses an issue encountered when creating a simple fmt.Fprintf wrapper that accepts a variable number of arguments.

Problem: Incorrect Output When Calling Wrapper

When calling the wrapper function Die("foo"), an unexpected output is produced: "foo%!(EXTRA []interface {}=[])". This raises two questions:

  • Why does this extra text appear after "foo"?
  • What is the correct way to create wrappers around fmt.Fprintf?

Solution: Using Spread Operator

Variadic functions in Go receive arguments as a slice. In this case, the wrapper function Die has a parameter args of type []interface{}. However, when passing this argument to fmt.Sprintf, it is treated as a single argument of type []interface{}.

To resolve this issue and pass each value in args as a separate argument, the spread operator (...) must be used. By adding this syntax to the fmt.Sprintf call, the individual values in args are expanded and passed accordingly:

str := fmt.Sprintf(format, args...)
Copy after login

This approach ensures that the wrapper function correctly passes the variable arguments to fmt.Fprintf.

The above is the detailed content of Why does 'foo%!(EXTRA []interface {}=[])' appear when calling a `fmt.Fprintf` wrapper with variadic arguments?. 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