Multiple-value Function() in single-value context (here below golang newbies code please don't laugh)


(Ajil Raju) #1
// program to find quotient and reminder

package main

import “fmt”

func main () {
fmt.Println (“5 / 3 , quotient and reminder”, DiviReminder (5, 3)) // problem here
}

func DiviReminder (a, b int64) (int64, int64) {

quotient := a / b
reminder := a % b

return quotient, reminder

}


(Jakob Borg) #2

Your function is returning two values. Println is (essentially) expecting just one value. So,

q, r := DiviReminder(...)
fmt.Println("...", q, r)

Now, the “essentially” above simplifies things a bit - Println takes a variable number of arguments, so you might think you could just do what you did and it would work. But it doesn’t due to how Go handles multiple return values in function calls. Basically, if the returned values exactly matches the parameters, you can do what you did with the function call as the only parameter:

func DiviReminder (a, b int64) (int64, int64) {
  ...
}

func PrintResults(q, r int64) {
  fmt.Println("The results were", q, "and" ,r)
}

func main() {
  PrintResults(DiviReminder(5, 3))
}

This doesn’t apply if you are also passing other parameters, or the function accepts a variable number of parameters though.


(Ajil Raju) #3

yes, this is very helpful


(Ajil Raju) #4

Format specifier %d can do anything in my code fmt.Println(%d%d, fun())


(László Nesztorov) #5

Hello,

fmt.Println(%d%d, fun()) // syntax error

Please, use :

fmt.Printf("%d %d", fun())


(Ajil Raju) #6

Okay okey I forgot " " thanks bro.