1. Variable exchange
A brief explanation of what variable exchange is, as the name suggests, is an action of exchanging the value of a variable
For example, we define two variablesa:=10
andb:=20
, then at this time, if we want to exchange the values of two variables, it provides us with a relatively convenient way in Go.
Case
package main import "fmt" func main() { // Define the variables a and b and assign values 10 and 20 respectively a, b := 10, 20 // View results for the first round of output ("The original result of a and b is:", a, b) // Then we can use the = sign to quickly assign a and b and exchange their positions a, b = b, a // View results for the second round of output ("The results of the new output a and b are:", a, b) }
Through the above code we can see that=
The right side of the word means assignment, because the code form of multiple assignments and multiple declarations is supported in Go, so we only need to switch the variables to be assigned to the position, and the new value will be assigned.
2. Anonymous variables
After explaining variable exchange, we have to mention a special existence in the variable, that is, anonymous variables
Assigning a value to an anonymous variable is actually equivalent to discarding this value. It is also commonly known as the abandonment value
Key logo
Use _ underscore to identify anonymous variables, which are what we call blank identifiers
Case
package main import "fmt" func main() { // Define variables _, a := 10, 7 // When using anonymous variables, 10 is to abandon the value ("Output result:", a) }
2.1. How to understand the usage scenario of this anonymous variable?
Many people may have questions about the significance of this anonymous variable. In fact, in actual use scenarios, the meaning of the use of anonymous variables is personally closer to a placeholder.
Suppose we use a function nameDial()
, this function will return two values to us, so we only need one of them, and we cannot use the other value, but because it is a return value, we need to receive it in the code rule, so at this time we can use anonymous variables to occupy the position of the other value, the code is as follows.
Case
package main import ( "fmt" "net" ) func main() { //conn, err := ("tcp", "127.0.0.1:8080") //If you don't want to receive the value of err, you can use _ to represent it, this is an anonymous variable conn, _ := ("tcp", "127.0.0.1:8080") (conn) }
Here()
The function has two return values, respectivelyconn,err
, then we only needconn
When this return value is used, we can use itAnonymous variables
To take up the placeholder to get another return value, but we don't need to use this return value.
3. About scope
A variable (constant, type, or function) has a certain scope of action in a program, and is called scope
First of all, the special nature of Go language leads to the fact that if the variables, constants, functions, etc. you defined are not used during the compilation process, the compilation cannot be passed, so it is necessary to understand the scope of action.
Understanding the scope can better define what you need to use, and can also solve some errors in the compilation process.
Three types of positions are summarized according to the definition
- The variables defined in the function are called local variables
- Variables defined outside the function are called global variables
- Variables in function definitions are called formal parameters
The so-called function can be temporarily understood as a piece of code snippet, such as the one commonly used in our case.main()
It's a function
Define content in function{ }
Inside, it can be called defined in the function body.
3.1. Local variables
Variables declared in the function body are called local variables. Their scope is only within the function body. The function's parameters and return value variables are both local variables.
(Extended) Local variables do not always exist. They only exist after the function that defines them is called. After the function call is finished, the local variable will be destroyed.
Case
package main import "fmt" func main() { // Define variables. The following definitions in the main() function can be called local variables a := 10 b := 20 c := a + b // Output local variables ("The output local variable is:", a, b, c) }
3.2. Global variables
Variables declared in the body of the function are called global variables. Global variables only need to be defined in one source file and can be used in all source files. Of course, source files that do not contain this global variable need to be introduced using the "import" keyword before using the source file where the global variable is located.
Global variable declarations must start with the var keyword. If you want to use it in an external package (that is, you want to be imported by another package), the first letter of the global variable must be capitalized.
Case
package main import "fmt" // Define global variables, you must have the var keyword, and outside the function bodyvar a = 10 var b = "let's go" func main() { // Call a and b in main() function ("The output global variable is:", a, b) demo() } func demo() { // Because it is used globally, our methods can be called in this source code // So I can also call the value of the b variable in the sum() function ("Callsum()The global variable output of the function is:", b) }
You can see the above case, both inmain()
The function is still in oursdemo()
In the function, we can all geta、b
The value of output
Usage details: What should I do about the global and local names?
You may think about a question, if I have a global variable calleda
, and at the same time, I also defined a local variable in the functiona
, the names of these two variables are the same but the values are different, so who should our program adopt?
In fact, most of the time when encountering this situation, the procedure generally followsThe principle of proximity
, that is to say, many times our program is used to be whoever is close to it.
In other words, when the above situation occurs, we will give priority to the closest ones.Local variables
Case
package main import "fmt" var a = "This is a global variable" func main() { a := "This is a local variable" ("The variables that will be used in main are:", a) demo() } func demo() { ("If there is no local variable effect: ", a) }
The result is:
The variables that will be used in main are: This is a local variable
If there is no local variable effect: This is a global variable
Note: Although this situation will occur, don't show such code that makes people easily ambiguity. Although the rules do not allow it, it is obviously wrong in the code specification.
3.3. Formal parameters
When defining a function, the variable in the parentheses after the function name is called formal parameters (referred to as formal parameters). Formal parameters will only take effect when the function is called, and will be destroyed after the function call is finished. When the function is not called, the formal parameters of the function do not occupy the actual storage unit and have no actual value.
Formal parameters are also declared local variables in a sense, so it is better not to have local variables duplicate names with formal parameters when defining local variables.
Case
package main import "fmt" // Define global variablesvar a = "This is a global variable" func main() { // Here are local variables a := "This is the local variable a of main" b := "This is the local variable b of main" ("The value of the output variable is: ", a, b) // Pass the values of local variables a and b when calling the test() function test(a, b) } // Define the formal parameters a and b in the function, then when the test() function is called// Formal parameters can be used directly as local variables, and the value is determined by the caller's passing contentfunc test(a, b string) { // Output result ("This is what is passed from main:", a, b) }
The output result is:
The value of the output variable is: This is the local variable of main a This is the local variable b of main
This is what is passed from main: This is the local variable of main a This is the local variable of main b
Through the above case, let us have an understanding of local variables, global variables, and formal parameters, and distinguish the differences and use between them.
4. About constants
When we begin to introduce constants in the code, we need to explain what constants are?
In fact, the so-called constant is a value that will not change, which is used to store some values that we have specified in advance and will not change.
4.1. Use of constants
Constant usage keywords in Go languageconst
Definition, used to store data that does not change, constants are created at compile time, even if the definition is inside a function, and can only be Boolean, numeric (integer, floating point, and complex) and string.
Due to compile-time limitations, the expression that defines a constant must be a constant expression that can be evaluated by the compiler.
grammar
// Pay attention to [] means that the data type can be written, but not writtenconst Constant name [Data Type] = value
From the previous variable declarations, we can know that Go often wants to simplify batch actions, so when defining constants, you can also use batch definitions.
Batch definition syntax
const ( Constant name1 = value1 Constant name2 = value2 ... )
All constant operations can be completed during the compilation period, which not only reduces the work at runtime, but also facilitates the compilation and optimization of other codes. When operands are constants, some runtime errors can also be discovered during compilation, such as integer division, string indexes out of bounds, any operations that lead to invalid floating point numbers, etc.
Case
// Single definition constantconst pi= 3.14159 // Batch definition constantsconst ( e = 2.7182818 pi = 3.1415926 )
4.2. Details of constant usage
In fact, in the process of using constants, in addition to defining constants in batch definition, we can also use another method to simplify the process of constant initialization (assignment) while defining constants in batches.
Simply put, suppose I want to definea、b、c、d
Four constants. The values of a and b are all defined as 10, and the values of c and d are all defined as 20. Then we can perform some simplified operations during initialization.
Case analysis
package main import "fmt" const ( a = 10 b c = 20 d ) func main() { ("Output definition constant:", a, b, c, d) }
The final output is:
The output definition constant: 10 10 20 20
4. Constant generator
Constant declarations can be initialized using the iota constant generator, which is used to generate a set of constants initialized with similar rules, but do not need to write the initialization expression once every line.
Simply put, it is a bit similar to a counter. When defining the first constant, it will be set to 0, and then 1 will be accumulated accordingly.
need
We may understand this better based on our needsiota
Suppose we want to define a constant from Monday to Sunday, then Monday is 0, and so on.
Case analysis
package main import "fmt" // Define Monday to Sundayconst ( Monday = iota Tuesday Wednesday Thursday Friday Saturday Sunday //6 ) func main() { ("The value of the output date is:", Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) }
The output result is:
The value of the output date is: 0 1 2 3 4 5 6
Of course we knowiota
The initial value of 0 by default, but as long as you perform calculation operations on iota in the first step, for exampleMonday = iota+1
, then you can find that when the initial value is changed, the subsequent values will also change one after another. You can try it!
Summarize
This is the end of this article about variables and constants in Go language. For more related Go variables and constants, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!