doushu0591
2014-08-13 09:22
浏览 31
已采纳

通过if语句进行多次赋值

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

}

图片转代码服务由CSDN问答提供 功能建议

是否可以通过if条件执行多个分配,例如以下代码?

  func SendEmail(URL,电子邮件字符串)(字符串,错误){
 
 genUri:= buildUri()
如果err:= setRedisIdentity(genUri,email);  err!= nil;  genUrl,err:= buildActivateUrl(url,genUri);  {
 return“”,err 
} 
 
返回“ test”,nil 
 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duandi1919 2014-08-13 11:28
    已采纳

    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
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doujiao3074 2014-08-13 09:54

    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
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题