Notes on the use of golang assignment and declaration syntax sugar

Time:2020-1-14

Assignment and declaration syntax sugar

Basic strategy, just search

Matters needing attention

Type inference

:=Type inference will be performed automatically. Type conversion is required when the desired type is not the one you want

//I1 defaults to int type
i1 := 1

//When you need to use I2 as Int64, you need to perform type conversion and reassignment
i2 := int64(1)

When it comes to type inference, I’ll mention const variable. If it’s const variable, the value defined in const variable will automatically determine the type at compile time according to the context

Existing variables in the same scope will not be recreated

:=The variables on the left are not all new variables. They may be old variables, but they have been reassigned. As long as they are existing variables in the same scope, new variables will not be created

// return 1
func testFunc() (ret int) {
    ret, err := 1, error(nil)
    if err != nil {
        return
    }
    return
}

Different scopes will create new variables

It’s a little different from the above

//Return 0. The RET of the return value is not assigned. The assigned value is the RET in the if, which is not related to the RET outside
func testFunc() (ret int) {
    if ret, err := 1, error(nil); err != nil {
        fmt.Println(ret)
        return
    }
    return
}

Recommended Today

Regular expression sharing for checking primes

This regular expression is shown as follows: Regular expressions for checking prime numbers or not To use this positive regular expression, you need to convert the natural number into multiple 1 strings. For example, 2 should be written as “11”, 3 should be written as “111”, 17 should be written as “11111111111”. This kind of […]