Home  >  Article  >  Backend Development  >  Why Does My fmt.Fprintf Wrapper Print Unexpected Output?

Why Does My fmt.Fprintf Wrapper Print Unexpected Output?

DDD
DDDOriginal
2024-11-12 22:51:02349browse

Why Does My fmt.Fprintf Wrapper Print Unexpected Output?

Passing Arguments to Variadic Functions

Variadic functions in Go accept a variable number of arguments, which are stored as a slice of the specified type. When calling a variadic function, it's essential to understand how arguments are passed.

Problem: Extra Output in fmt.Fprintf Wrapper

Consider the following code that attempts to create a wrapper around fmt.Fprintf with variable-length arguments:

func Die(format string, args ...interface{}) {
    str := fmt.Sprintf(format, args)
    fmt.Fprintf(os.Stderr, "%v\n", str)
    os.Exit(1)
}

When calling Die("foo"), the output contains the unexpected "%%!(EXTRA []interface {}=[])".

Solution: Using Ellipsis ... to Pass Arguments

The issue arises from passing the args slice directly to fmt.Sprintf. To correctly pass arguments individually, the ellipsis operator ... must be used:

package main

import (
    "fmt"
    "os"
)

func Die(format string, args ...interface{}) {
    str := fmt.Sprintf(format, args...)
    fmt.Fprintf(os.Stderr, "%v\n", str)
    os.Exit(1)
}

func main() {
    Die("foo")
}

By using ..., each element of the args slice is passed as a separate argument to fmt.Sprintf, resolving the issue and producing the expected output:

foo

The above is the detailed content of Why Does My fmt.Fprintf Wrapper Print Unexpected Output?. 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