Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple assignment by if statement

Tags:

go

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

}
like image 389
softshipper Avatar asked Aug 13 '14 09:08

softshipper


People also ask

What is multiple assignment statement?

multiple assignment A form of assignment statement in which the same value is given to two or more variables. For example, in Algol, a := b := c := 0. sets a, b, c to zero. A Dictionary of Computing. "multiple assignment ."

Is multiple assignment possible in c++?

Multiple assignment. I haven't said much about it, but it is legal in C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value.

Can you assign multiple variables at once?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

What is multiple assignment in Python?

Python allows you to assign a single value to several variables simultaneously. For example − a = b = c = 1. Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables.


2 Answers

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
like image 88
peterSO Avatar answered Oct 25 '22 07:10

peterSO


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
}
like image 44
Bryan Avatar answered Oct 25 '22 09:10

Bryan