vendredi 23 novembre 2018

Go: "if" initialization statement with methods that have multiple return values

I would like to have initialization statement in my if statement that actually uses several methods that return several values. Example:

func HandleArgs(args ...interface{}) {
     // Some additional checks here

     if value1, ok1, value2, ok2 := args[0].(string), args[1].(string); ok1 && ok2 {
          // Do something
     }
}

Go doesn't allow me to do that, responding with error:

assignment mismatch: 4 variables but 2 values

It is even more confusing considering that compiler can easily handle one method that return 2 values:

// it is OK!
if value, ok := args[0].(string); ok {
}

Is there any way to do what I want aside of dividing one if statement into two, which is ugly?

Aucun commentaire:

Enregistrer un commentaire