Print string and return values of a function with Println

package main

import (
	"fmt"
)


func main() {
	fmt.Println("random text",test(1,2))
}

func test(int,int) (int,int) {
	return 3, 4
}

I was expecting the following result of above code

random text 3 4

But instead I got the error

multiple-value test() in single-value context

How do I get the expected output.

Hi Rahul,

The test function returns two ints - 3 and 4

Hence,

package main

import (
	"fmt"
)


func main() {
    a, b := test(1,2)
	fmt.Println("random text", a, b)
}

func test(int,int) (int,int) {
	return 3, 4
}

This would work. You can use only single return value functions directly in a print statement. There are other complicated ways to accommodate that, but for now this is the simple way.

You can use only single return value functions directly in a print statement

fmt.Println(test(1,2))

works perfectly giving the output

3 4

then why does

fmt.Println("random text",test(1,2))

fail?

I’ve never given print statements with a function alone (Always will have some string message) . Used to doing it the way I mentioned.

You are right. I tried with other return types as well. Same behavior. There must be some reason behind it. Lets see what the others have to say. Might be something obvious.

@jayts Since you are the expert! :slight_smile:

https://golang.org/ref/spec#Calls

As a special case, if the return values of a function or method g are equal in number and individually assignable to the parameters of another function or method f, then the call f(g(parameters_of_g)) will invoke f after binding the return values of g to the parameters of f in order. The call of f must contain no parameters other than the call of g, and g must have at least one return value. If f has a final … parameter, it is assigned the return values of g that remain after assignment of regular parameters.

func Split(s string, pos int) (string, string) {
	return s[0:pos], s[pos:]
}

func Join(s, t string) string {
	return s + t
}

if Join(Split(value, len(value)/2)) != value {
	log.Panic("test fails")
}

So calling a function given one function with multiple returns as only parameter is allowed.

2 Likes

It looks like Johan’s answer is perfect. :slight_smile:

2 Likes

Thanks for the clarification @johandalabacka and @jayts ! :slight_smile:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.