user6638302
user6638302

Reputation:

How to return only one variable in multi return function in GO?

Hi I have this function which I want to return a docker.APIContainer and an error (nil if no errors), but in case of error what should I return in docker.APIContainer ?

this is the code

func GetContainersRunningImage(imagename string, tag string) ([]docker.Container,string) {
   logFields := log.Fields{

       "handler": "get service",
   }
   client, err := docker.NewTLSClient(sconf.DockConf.Endpoint, sconf.DockConf.Cert, sconf.DockConf.Key, sconf.DockConf.Ca)
   if err != nil {
      log.WithFields(logFields).Errorf("TLSClient could not be created: %s", err)
      return _,err.Error()
   }
}

what should I add instead of _? Am I obliged to create a var contarray []docker.Container and return it? or is there another way

Upvotes: 1

Views: 1024

Answers (2)

Endre Simo
Endre Simo

Reputation: 11541

GetContainersRunningImage returns multiple values: a []docker.Container and a string, which means you have to return two values with exactly the same type signatures, or nil in case you do not want to return a concrete value.

Because you are handling the error case it's ok to return a nil value in case of an error:

if err != nil {
      log.WithFields(logFields).Errorf("TLSClient could not be created: %s", err)
      return nil, err.Error()
}

But you have to return a value at the end of the function in case you don't receive an error. In this case the type signature of the return function should be of type: []docker.Container, string.

That's why in Go the idiomatic way of a function return argument is the value and an error if an error has occurred. Because you are handling the error separately in an if statement which returns two values: nil instead of the value and the error type, the final return should be the type value and nil for error.

func GetContainersRunningImage(imagename string, tag string) ([]docker.Container,string) {
   var contarray []docker.Container

   logFields := log.Fields{

       "handler": "get service",
   }
   client, err := docker.NewTLSClient(sconf.DockConf.Endpoint, sconf.DockConf.Cert, sconf.DockConf.Key, sconf.DockConf.Ca)
   if err != nil {
      log.WithFields(logFields).Errorf("TLSClient could not be created: %s", err)
      return nil, err.Error()
   }

   return contarray, nil
}

Other possibility is to use the _(underscore) variable to disregard one of the return values, but this needs to happen on variable assignment.

Upvotes: 1

huygn
huygn

Reputation: 1008

return nil, err.Error()

goreturns will do this for you automatically - 0 for int and "" for string etc.

Upvotes: 0

Related Questions