I have a Go function which returns two integer values. Below is the function
func temp() (int, int){
return 1,1
}
Is it possible to put temp
function directly into a Println
and print both the outputs using string formatting as below:
fmt.Println("first= %d and second = %d", temp() ) // This doesn't work
In Python, I am able to do the following:
def func():
return 1,1
print("{0}={1}".format(*func())
>> '1=2'
Can I do Something similar in Go too?
Foreword: I released this utility in
github.com/icza/gox
, seegox.Wrap()
.First, for what you attempt to do you should use
fmt.Printf()
instead offmt.Println()
as only the former expects and uses a format string.Going forward, this isn't supported by default, because quoting from Spec: Calls:
And
fmt.Printf()
has a signature of:You cannot pass other parameters to
fmt.Printf()
besides a function call (the return values of the call).Note that the signature of
fmt.Println()
is:Which means that
fmt.Println(temp())
works, and so does with any other functions that have at least one return value, because the last sentence of the quoted part allows this ("Iff
has a final...
parameter, it is assigned the return values ofg
that remain after assignment of regular parameters.")But with a little trick we can achieve what you want with
fmt.Printf()
too.Note that if
temp()
would return a value of type[]interface{}
, we could use...
to pass it as the value of some variadic parameter.Meaning this works:
And it properly prints (try it on the Go Playground):
So we just need a utility function that wraps the return values of any function into a
[]interface{}
, and so we can use this to pass tofmt.Printf()
.And it's dead-simple:
As detailed above (with
fmt.Println()
), we can pass the return values of any function that has at least 1 return value towrap()
as the values of its input parameters.Now using this
wrap()
function, see the following example:This works, and it outputs (try it on the Go Playground):
For more on the topic, see related question:
Multiple values in single-value context
Return map like 'ok' in Golang on normal functions