通过if语句进行多重赋值

huangapple go评论94阅读模式
英文:

Multiple assignment by if statement

问题

可以通过if条件执行多个赋值吗?就像下面的代码一样?

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

}

是的,可以在if条件中执行多个赋值操作。在你提供的代码中,if语句中的第一个赋值是err := setRedisIdentity(genUri, email),第二个赋值是genUrl, err := buildActivateUrl(url, genUri)。这两个赋值操作都会在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

}

答案1

得分: 25

看起来你想要这样的代码:

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")
}

输出结果:

sometimes
always
英文:

It looks like you want something like this:

package main

import &quot;fmt&quot;

func a(int) int { return 7 }

func b(int) int { return 42 }

func main() {
	if x, y := a(1), b(2); x &gt; 0 &amp;&amp; x &lt; y {
		fmt.Println(&quot;sometimes&quot;)
	}
	fmt.Println(&quot;always&quot;)
}

Output:

sometimes
always

答案2

得分: 13

不。if语句的开始只允许有一个“简单语句”,根据规范

推荐的方法是多个可能返回错误的测试,所以我认为你想要的是这样的:

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
}
英文:

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 &quot;&quot;, err
    }  
    if genUrl, err := buildActivateUrl(url, genUri); err != nil {
        return &quot;&quot;, err
    }
    return &quot;test&quot;, nil
}

huangapple
  • 本文由 发表于 2014年8月13日 17:22:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/25282572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定