Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variadic functions parameters pass-through

Situation:

I'm trying to write a simple fmt.Fprintf wrapper which takes a variable number of arguments. This is the code:

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

Problem:

When I call it with Die("foo"), I get the following output (instead of "foo"):

foo%!(EXTRA []interface {}=[])

  • Why is there "%!(EXTRA []interface {}=[])" after the "foo"?
  • What is the correct way to create wrappers around fmt.Fprintf?
like image 276
ivanzoid Avatar asked Sep 08 '12 21:09

ivanzoid


People also ask

What is variadic parameters in go?

A variadic function is a function that accepts a variable number of arguments. In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature.

Can variadic methods take any number of parameters?

A variadic function allows you to accept any arbitrary number of arguments in a function.

What are variadic parameters in Python?

Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.


1 Answers

Variadic functions receive the arguments as a slice of the type. In this case your function receives a []interface{} named args. When you pass that argument to fmt.Sprintf, you are passing it as a single argument of type []interface{}. What you really want is to pass each value in args as a separate argument (the same way you received them). To do this you must use the ... syntax.

str := fmt.Sprintf(format, args...) 

This is also explained in the Go specification here.

like image 82
Stephen Weinberg Avatar answered Sep 22 '22 10:09

Stephen Weinberg