2

Hello everyone, I am fried fish.

A reader who just got started with Go raised an interesting question: Go has several ways to declare variables. As a beginner, which one should be used, what is the difference, and why are there multiple ways of declaring variables?

To this end, Fried Fish will explore this issue with you.

variable declaration

In Go, there are two ways to declare variables, each with different usage scenarios.

They are:

  • Standard variable declarations (Variable declarations).
  • Short variable declarations

Standard Statement

A variable declaration creates one or more variables, binds them with corresponding identifiers, and gives each variable a type and initial value.

Use syntax:

VarDecl     = "var" ( VarSpec | "(" { VarSpec ";" } ")" ) .
VarSpec     = IdentifierList ( Type [ "=" ExpressionList ] | "=" ExpressionList ) .

Case code:

var i int
var U, V, W float64
var k = 0
var x, y float32 = -1, -2
var (
    i       int
    u, v, s = 1.0, 2.0, "脑子进煎鱼了"
)

short statement

A short variable declaration. Use syntax:

ShortVarDecl = IdentifierList ":=" ExpressionList .

Case code:

s := "煎鱼进脑子了"
i, j := 0, 10
f := func() int { return 7 }
ch := make(chan int)
r, w, _ := os.Pipe()
_, y, _ := coord(p) 

Netizens doubt

After the Go readers in our group asked this question, I also searched for relevant information. I found that some people have raised similar doubts on stackoverflow:

The problem is: which declaration to use, it's confusing.

The reason for the confusion is that:

  • If one is just a shorthand for the other, why do they behave differently?
  • Why did the authors of Go have two ways to declare a variable (why not combine them into one)? Just to confuse us?
  • Is there any other aspect that I need to pay attention to when using it, so as not to fall into the pit?

Below we combine this question and answer from stackoverflow to further expand.

Think about it: standard declarations and short declarations, what's the difference between the two, or use them at will?

where is the difference

Grouping declarations of code blocks

When using the declaration syntax that includes the keyword var, as with other keywords such as package, import, const, type, var, etc., it is possible to declare blocks of code that can be grouped.

For example:

var (
    i       int
    u, v, s = 1.0, 2.0, "脑子进煎鱼了"
)

And short declarations are not supported.

The initial value of the variable is specified

When using the standard variable definition, we can just declare, not actively define the initial value of the variable (the default will be zero).

For example:

var (
    i    int
    s    string
)

The short declaration is not good, you must actively define a value for the variable in the program.

For example:

s := "脑子进煎鱼了"

Even if it is an empty string defined here, it is actively defined by the user, rather than the default zero value.

local variables, scoped

When writing programs, we often have some local variable declarations, and the scope is limited.

You can look at your own code. In this case, we will all take a short statement.

For example:

for idx, value := range array {
    // Do something with index and value
}

if num := runtime.NumCPU(); num > 1 {
    fmt.Println("Multicore CPU, cores:", num)
}

Short declarations have clear advantages in such scenarios, where standard variable declarations are unflattering.

redeclare variable

It is clearly mentioned in the Go language specification that short variable declarations can redeclare variables, which is an overriding action of frequent redeclaration.

as follows:

var name = "煎鱼.txt"

fi, err := os.Stat(name)
if err != nil {
    log.Fatal(err)
}

data, err := ioutil.ReadFile(name)
if err != nil {
    log.Fatal(err)
}
...

In the above code, the err variable is defined repeatedly. if err != nil rampant, the advantage of short variables here is simply a big killer.

Summarize

I believe that many small partners have struggled with this when they first started, or many tutorials did not clearly explain the difference between the two variable declarations.

In today's article, we introduced two types of variable declarations in Go. And the scenarios where short declarations exist are explained.

mainly:

  • Grouped declarations of code blocks.
  • The initial value of the variable is specified.
  • Local variables are scoped.
  • Redeclare the variable.

Do you think there are other advantages and disadvantages of variable declaration? Welcome to communicate in the comment area :)

If you have any questions please comment and feedback exchange area, best relationship is mutual achievement , everybody thumbs is fried fish creation of maximum power, thanks for the support.

The article continues to be updated, you can read it on search [brain fried fish], this article 161e4fee3232b4 GitHub github.com/eddycjy/blog has been included, learn Go language can see Go learning map and route

refer to


煎鱼
8.4k 声望12.8k 粉丝