Can you declare multiple variables at once in Go?

前端 未结 6 1273
鱼传尺愫
鱼传尺愫 2020-12-01 15:36

Is it possible to declare multiple variables at once using Golang?

For example in Python you can type this:

a = b = c = 80

and all

6条回答
  •  悲哀的现实
    2020-12-01 16:16

    Yes you can and it is slightly more nuanced than it seems.

    To start with, you can do something as plain as:

    var a, b, x, y int  // declares four variables all of type int
    

    You can use the same syntax in function parameter declarations:

    func foo(a, b string) {  // takes two string parameters a and b
        ...
    }
    

    Then comes the short-hand syntax for declaring and assigning a variable at the same time.

    x, y := "Hello", 10   // x is an instance of `string`, y is of type `int`
    

    An oft-encountered pattern in Golang is:

    result, err := some_api(...)  // declares and sets `result` and `err`
    if err != nil {
        // ...
        return err
    }
    
    result1, err := some_other_api(...)   // declares and sets `result1`, reassigns `err`
    if err != nil {
        return err
    }
    

    So you can assign to already-defined variables on the left side of the := operator, so long as at least one of the variables being assigned to is new. Otherwise it's not well-formed. This is nifty because it allows us to reuse the same error variable for multiple API calls, instead of having to define a new one for each API call. But guard against inadvertent use of the following:

    result, err := some_api(...)  // declares and sets `result` and `err`
    if err != nil {
        // ...
        return err
    }
    
    if result1, err := some_other_api(...); err != nil {   // result1, err are both created afresh, 
                                                           // visible only in the scope of this block.
                                                           // this err shadows err from outer block
        return err
    }
    

提交回复
热议问题