Multiple assignment by if statement

2020-06-04 03:23发布

问题:

It is possible to execute multiple assignment by if condition, like the following code?

func SendEmail(url, email string) (string, error) {

    genUri := buildUri()
    if err := setRedisIdentity(genUri, email); err != nil; genUrl, err := buildActivateUrl(url, genUri);  {
        return "", err
    }  

    return "test", nil

}

回答1:

No. Only one 'simple statement' is permitted at the beginning of an if-statement, per the spec.

The recommended approach is multiple tests which might return an error, so I think you want something like:

func SendEmail(url, email string) (string, error) {
    genUri := buildUri()
    if err := setRedisIdentity(genUri, email); err != nil {
        return "", err
    }  
    if genUrl, err := buildActivateUrl(url, genUri); err != nil {
        return "", err
    }
    return "test", nil
}


回答2:

It looks like you want something like this:

package main

import "fmt"

func a(int) int { return 7 }

func b(int) int { return 42 }

func main() {
    if x, y := a(1), b(2); x > 0 && x < y {
        fmt.Println("sometimes")
    }
    fmt.Println("always")
}

Output:

sometimes
always


标签: go