Understand compile error

I am trying to understand why I see compile error when I uncomment line # 11 in the code below

  1 package main
  3 import "fmt"
  5 func main() {
  6    half := func(n int) (int, bool) {
  7       return n/2, n%2 == 0
  8    }
 10     // Uncommenting the code below results in compile error.  Why ??
 11    // fmt.Println("Return from half(1) ", half(1))
 13    // Compiles fine.
 14    // I want to print a string that gives a meaningful
 15    // message to the user.
 16    fmt.Println(half(1))
 17 }

Compile error I see is -

$ go build func_ex2.go


.\func_ex2.go:11: multiple-value half() in single-value context

I have Println() in line #16 and compiles fine. I want to give some meaningful message to the user like in line #11.

I am new to golang and any help appreciated.

Sudheendra G Sampath

The fmt.Print statement needs a interface type (https://golang.org/pkg/fmt/)
If you define a struct with the structure of the arguments of your func, Print will accept it.
See two methods https://play.golang.org/p/B4cL8uaYJm

Println is defined as

func Println(a ...interface{}) (n int, err error)

so it takes an arbitrary number of interface{} values as parameters. Each of the interface{} parameters can only be single-valued.
In the case of


Println receives two single-valued parameters, one int and one bool, and this works fine.
However, in case of

    fmt.Println("Return from half(1) ", half(1))

Println receives one single-valued parameter (the string) and one two-valued parameter (the output of half()), and the second one cannot be assigned to a single interface{} value.

It would indeed come in handy if Println had some ‘magic’ here for spreading the output of half() over two interface{} parameters. Luckily the workaround is easy:

a, b := half(1)
fmt.Println("Return from half(1)", a, b)

or use the struct approach that Costa_Konstantinidis proposed just a few minutes ago (while I was writing this :))

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