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

Why Does My fmt.Fprintf Wrapper Print Unexpected Output?

DDD
Release: 2024-11-12 22:51:02
Original
437 people have browsed it

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

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")
}
Copy after login

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

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!

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