[Golang Base] local variable initialization: =

Source: Internet
Author: User

a basic usage

Action: = can only be used inside a method, declaring and initializing a new variable

3

But cannot be used to assign values to declared variables, the following procedure compiler will report the error "No new variables on the left side of: ="

var int 0 V: 1

Through the error can be learned that: = operation must have a new variable on the left, then the initialization of multiple variables only need to meet the left at least one new variable can be

ERR: = errors. New ("error1") ret, err:= Test_fun ()

This is legal, because RET is a new variable, which is convenient because the Go method often returns error err, so within the same method

Just declare an ERR variable to

Two: = Trap

Since: = can only be used for local variables, what happens to the following code?

var  out int 1 func Test () {    outof23      }

The scope of the variable out contains test (), but in fact: the operation creates a new local variable out, which you should remember!!!

So a similar scenario:

func test1 () {    V:1    {        V:1    }    }

Will the compiler report "No new variables on the left side of: ="? The compiler does not have an error, so two V is a different variable

If for switch in go can produce a special scoped local variable, you need to be aware of the variable assignment in the IF for switch: =

Conclusion:

1: = local variable on the left side of the same scope, only assignment operation, no newly generated local variable

2: The local variable with the upper scope appears on the left, and a new local variable with the same name is generated and assigned

3: = left non-local variable, generating local variable with the same name as the non-local variable

[Golang Base] local variable initialization: =

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.