go language core 36 lecture (GO language basic knowledge IV) - Learn notes

04 | Things of the program entity (on)

Remember? Program entities in the Go language include variables, constants, functions, structures, and interfaces. The Go language is a static type of programming language, so we need to specify their type when declaring variables or constants, or give enough information so that the Go language can be derived.

Problem: How many ways to declare variables?

package main

import (

func main() {
  var name string // [1]
  flag.StringVar(&name, "name", "everyone", "The greeting object.") // [2]
  fmt.Printf("Hello, %v!\n", name)

This is a very simple command source file, I named it Demo7.go. It is the fine tuning version of Demo2.go. I just move the declaration of the variable Name and the call to the flag.stringvar function to the main function, which corresponds to the comments in the code [1] and [2].

The specific problem is that in addition to the way var Name String this declared variable Name, have other ways? You can selectively change the code at [1] and [2].

Typical answer

The first way needs to be changed to the code in the comment [2], and the called function is changed from flag.stringvar to flag.string, and the list of pass parameters needs to be modified, this is for [1 And [2] The acquisition work is prepared.

var name = flag.String("name", "everyone", "The greeting object.")

The merged code looks more concise. I dropped the string in the code of [1], and one = on the right, then spliced ​​the modified [2] code.

Note that the type value of the result value returned by the flag.string function isString instead of string. typeString represents a string’s pointer type instead of a string type. Therefore, the variable Name here is a pointer to a string value.

Therefore, in this case, the function call that is used to print content needs to be fine-tuned, and the parameter NAME is changed to * name, namely: fmt.printf (“Hello,% v! \ N”, * name).

The second method is very similar to the first mode. It is based on the first way, the value symbol = the code on the right is not moving, leaving only Name on the left, and then turn = to: =.

name := flag.String("name", "everyone", "The greeting object.")

Question analysis

There are two basic test sites for this issue. One is that you have to know the type inference in the Go language, and the basic manifestation it in the code, the other is the usage of short variable declarations.

The code in the first mode is also assigned a value while declaring the variable Name, and there is no explicit specifying the type of NAME in this statement.

Remember? The previous variable declaration statement is Var name string. Here, the type of Go language itself uses, and the statement of the type of the variable is eliminated.

You can think that the expression type is the type of result after evaluating the expression. The type in the Go language is inference is very simple, which is also the style of the GO language.

It can only be used to initialize the variable or constant, just as described in the above answer. The call to the Flag.String function is actually a call expression, and this expression is * String, ie the type of string.

As for the short variable declaration used in the second way, it is actually the type in which the Go language is inferred, plus a little syntax sugar.

We can only use short variable declarations inside the function. When writing if, for or switch statements, we often insert it in the initialization clause and use to declare some temporary variables. In contrast, the first way is more common, it can be used anywhere.


Knowledge expansion

1. What are the benefits of the type of Go language?

Of course, when you write the code, we infer the type of Go language, and the number of keystrokes that save the keyboard can almost ignore. But it really benefits, often reflects those things after we write code, such as code reconstruction.

In order to better demonstrate, we must do a little preparation. We still assign a function to declare the Name variable while declaring the Name variable, but this function is not flag.string, but a function defined by our own, such as gettheflag.

package main

import (

func main() {
  var name = getTheFlag()
  fmt.Printf("Hello, %v!\n", *name)

func getTheFlag() *string {
  return flag.String("name", "everyone", "The greeting object.")

We can use the getTheflag function parcel (or package) that call to the flag.string function, and directly as the result of the getTheflag function, the result is * String.

This way, VAR name = The expression on the right can become a call expression for the getTheflag function. This is actually a reconstruction of “declaration and assigning Name variables”.

We usually do not change any of the interactive ways and rules of a program and the outside, and only change its internal implementation “code modification, called the reconstruction of the program. Reconstructive objects can be a line of code, one function , A functional module, or even a software system.

Ok, after the preparation work is finished, you will find that you can change the internal implementation of the GetTheflag function, and the type of return result without modifying any code in the main function.

This command source file can still be compiled, and there will be no problem with building and running. Maybe you can feel that this is a questionation about the flexibility of the program.

We do not explicitly specify the type of variable Name so that it can be given any type of value. That is, the type of variable Name can be dynamically determined by other programs when it is initialized.

After you change the result type of the getTheflag function, the patron of the Go language automatically updates the type of the variable Name when you build the program again. If you use Python or Ruby’s dynamic type programming language, you will feel this scenario.

Yes, through this type inference, you can experience a part of the advantages of dynamic type programming languages, that is, the programs flexibility is significantly improved. However, in those programming languages, this increase can be said to be exchanged with the maintenanceability and operational efficiency of the program.

go language is static type, so once it is determined when the initialization variable is determined, it is impossible to change again. This avoids some problems when maintaining procedures behind. Also, remember that this type of determination is done in the compile period, so there is no impact on the running efficiency of the program.

Now, you should have had a deep understanding of this issue.

If you only answer this question with one or two sentences, I think it can be like this: the type of Go language can significantly improve the flexibility of the program, making the code reconstruction easier, and will not give code Maintenance brings an additional burden (in fact, it can avoid bulletous code modifications), which will not lose the operational efficiency of the program.

2. What is the meaning of the variable?

This involves short variable declarations. By using it, we can focus on variables in the same code block.

Since I said the code block, let me first explain it. In the Go language, the code block is typically a zone enclosed by the curly parentheses, which can contain expressions and statements. The Go language itself and the code we have written together have formed a very large code block, also called the whole area code block.

Back to the problem of variable redeclaration. Its meaning is a declaration of the variable that has already been declared. The prerequisite for variable recommends is as follows.

  • Since the type of variable has been determined when its initialization is initialized, the type given when it again declares must be the same as its original type, otherwise the compilation error will be generated.
  • The heavy declaration of variables may only occur in a block. If the current variable is renamed is the variable in the outer code block, then it is another meaning.
  • The heavy declaration of variables only happens when using a short variable declaration, otherwise it will not be compiled. If you want to declare a new variable here, you should use a statement that contains keyword var, but you can’t be renowned with any variables in the same code block.
  • Variables that are “declared and assigned” must be multiple, and at least one of them is a new variable. At this time, we can say that the old variables are repeated.

In this way, the variable is strongly declared is actually a syntax (or convenient measures). It allows us to contain old variables in multiple variables that are assigned to assign values ​​when using short-variable declarations. You can imagine, if you don’t write many code more.

I wrote a simple example in the Demo9.go file in the Puzzlers / Article4 / Q3 package of the “golang_puzzlers” project, you can go.

​​The most important two lines of lines of this are as follows:

var err error
n, err := io.WriteString(os.Stdout, "Hello, everyone!\n")

I use short variable declarations to “declare and assign the value” for the new variable N and the old variable ERR, and the heavy declaration of the latter.


In this article, we focus on the most basic GO language program entities: variables. And detailed explanation of the basic method of variable declaration and assignment, and important concepts and knowledge behind it. We use keyword VARs and short variable declarations to implement the “declaration and assignment” of variables.

These two ways have a thousand autumn, with their own characteristics and applicable scenes. The former can be used anywhere, while the latter can only be used in functions or other smaller code blocks.

However, we can’t make heavy declarations for existing variables through the former, that is, it cannot handle the new old variables mixed together. However, they also have a very important common point, namely, based on type inference, the type inference of the Go language is only applied to the initialization of variables or constants.


If the current variable is renamed is the variable in the outer code block, then what does this mean?


This work is adoptedKnowledge sharing signature – non-commercial use – Sharing 4.0 International License Agreement in the same wayPermit.

Welcome to reprint, use, re-release, but must retain articles Zheng Zi Ming (including link:http://www.cnblogs.com/MingsonZheng/) Do not use commercial purposes, based on the modified works of this article must be released in the same license.