英文:
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 "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
答案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 "", err
}
if genUrl, err := buildActivateUrl(url, genUri); err != nil {
return "", err
}
return "test", nil
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论