The redeclare variable of go is a small pitfall of golang.

Source: Internet
Author: User

There are several ways to declare variables in go:

1. Declare with the keyword VaR

For example, var I int and then assign a value. I = 5.

2. The simplest method is to declare and assign values using the symbol: =.

For example, I: = 5 golang will default its type

Next let's look at a piece of code. First we declare a variable A, and then re-declare the variables A and B. In this function, variable A is declared twice, redeclare, And the execution result is 23.

Package main

Import (

"FMT"

)

Func main (){

A: = 1

A, B: = 2, 3

FMT. println (A, B)

}

The wonderful part is coming. Please refer to the second code

Package main

Import (

"FMT"

)

Type a struct {

I int

}

Func main (){

Testa: = & {}

Testa. I = 1

Testa. I, B: = 2, 3

FMT. println (testa. I, B)

}

We have defined a simple struct a. The member variable in a is I. i, B: = 2 and 3 new comments and assignments are made to member variables, and an error is reported during execution.

Cause: this issue was discussed on Google.

Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block with the same type, and at least one of the non-blank variables is new. as a consequence, redeclaration can only appear in a multi-variable short declaration. redeclaration does not introduce a new variable; it just assigns a new value to the original.
From the spec of go, redeclare is a value assignment instead of creating a new variable. Why is it not possible for a member variable? It can only be understood as a design problem for the moment. Here is a small pitfall, note the following when playing golang:
Related Article

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.