lundi 14 septembre 2020

Can I initialise multiple variables at the beginning of an if block using multiple functions with multiple return values?

I'm trying to use two functions to initialise variables inside an if block. Both functions return a bool value and an error. I have tried the following, but with no success. Is there a way to do what I'm trying to do?

func returnAValueAndError() (bool, error) {
    return true, nil
}

func alsoReturnAValueAndError() (bool, error) {
    return false, nil
}

if a, _ := returnAValueAndError(), b, _ := alsoReturnAValueAndError(); a || b {
//    this gives me
//    ./prog.go:16:42: syntax error: unexpected :=, expecting {
}

if a, _ := returnAValueAndError(); b, _ := alsoReturnAValueAndError(); a || b {
//    this gives me
//    ./prog.go:16:42: syntax error: cannot use b, _ := alsoReturnAValueAndError() as value
//    ./prog.go:17:38: syntax error: unexpected newline, expecting comma or }
}

if a, _, b, _ := returnAValueAndError(), alsoReturnAValueAndError(); a || b {
//    this gives me
//    ./prog.go:16:16: assignment mismatch: 4 variables but returnAValueAndError returns 2 values
//    ./prog.go:16:39: multiple-value returnAValueAndError() in single-value context
//    ./prog.go:16:67: multiple-value alsoReturnAValueAndError() in single-value context
}

Aucun commentaire:

Enregistrer un commentaire