How to correctly declare and assign variables in Go language
Go language is a statically typed programming language, and variables must be declared before use. In the Go language, the syntax for variable declaration is: var variable name variable type.
Global variables are declared as follows:
var globalVar int
Local variables are declared as follows:
func main() { var localVar int }
Declare and assign variables
In Go language, you can also declare and assign variables with the following syntax:
var a int = 10
If the type of the variable can be inferred, you can also use := to declare and assign variables:
b := 20
Explicit declaration and assignment
var c int c = 30
Multiple variable declaration
In the Go language, multiple variables can be declared at the same time, and To assign values to them, the syntax is as follows:
var d, e int = 40, 50
You can also use := to declare multiple variables and assign values at the same time:
f, g := 60, 70
Global Initialization of variables
When declaring a global variable, if you want to initialize a variable, you can use the init function, as shown below:
var globalVar int func init() { globalVar = 80 }
Declaration and assignment of constants
In Go In the language, constants are declared using the const keyword. Constants must be assigned a value when declared and are not allowed to be assigned again. Example:
const pi = 3.14159
Anonymous variable
In the Go language, _ is used to represent an anonymous variable, which is used to ignore a return value or unnecessary variables. Example:
_, result := divide(10, 2)
Summary:
In the Go language, correct declaration and assignment of variables is the basis for writing programs. Correct variable declaration can improve the readability and robustness of the program. Through the introduction of this article, readers can learn how to correctly declare and assign variables in the Go language, and master the skills of using different variable declaration and assignment methods. I hope readers can deepen their understanding of Go language variable declaration and assignment through practical operations.
[Note] The code examples are for reference only, please use them flexibly according to the actual situation.
The above is the detailed content of How to declare and assign variables correctly in Go language. For more information, please follow other related articles on the PHP Chinese website!