1. Variables and Constants
In Golang, variables and constants are two fundamental concepts that play a very important role in a program.
- A variable is a named identifier used to store data in a program. In Golang, the
var
keyword is used to declare variables. - A constant is an identifier whose value cannot be changed in the program. In Golang, the
const
keyword is used to declare constants.
2 Declaration and Initialization of Golang Variables
2.1 Declaration and Assignment of a Single Variable
In Go language, the var
keyword is used to declare a variable with the format var variable_name type
. After declaration, the variable can be assigned a value in the subsequent code, or it can be directly initialized at the time of declaration. For example:
var age int // Declare an integer variable age
age = 25 // Assign a value to the variable
var name string = "Alice" // Declare and initialize the variable name
2.2 Declaration of Multiple Variables
Go language supports the simultaneous declaration of multiple variables, which can make the code more concise. Bulk declaration is usually done at the beginning of a function or at the package level. For example:
var (
firstName, lastName string
age int
)
firstName = "John"
lastName = "Doe"
age = 30
In the above bulk declaration, firstName
and lastName
are declared as strings, while age
is an integer.
2.3 Type Inference and Short Variable Declaration
In Go language, it is not always necessary to explicitly specify the type of the variable. If an initialization expression is provided when declaring a variable, Go can infer the variable's type. This is known as type inference. Short variable declaration using :=
can simplify the statement for declaring and initializing variables based on type inference. For example:
city := "Beijing" // Using short variable declaration to simultaneously declare and initialize city
country := "China" // country is inferred as a string type
It's worth noting that short variable declarations can only be used inside functions and cannot be used at a global scope.
2.4 Variable Declaration Outside Functions
Variables declared outside functions have package-level scope. These variables are visible and accessible throughout the entire package. For example:
var globalVar string = "I am global" // Declaration of a global variable
func printGlobalVar() {
fmt.Println(globalVar) // Accessing the global variable inside the function
}
Global variables can be shared between any functions within the package, but should be used carefully to avoid potential naming conflicts and unclear references.
Tip: Understanding the basic function code here is sufficient, detailed explanations of functions will be provided in later sections.
3 Basic Data Types and Zero Values
3.1 Basic Data Types in Golang
In Go language, each type of variable provides explicit semantics and behavioral characteristics. Here are some common basic data types:
-
int
,int8
,int16
,int32
,int64
: Different ranges of integers -
uint
,uint8
,uint16
,uint32
,uint64
: Unsigned integers -
float32
,float64
: Floating-point numbers -
bool
: Boolean values (true or false) -
string
: Strings
3.2 Concept of Zero Values
In the Go language, variables are automatically initialized to their type's zero value after declaration. Zero value refers to the default value of the corresponding type when a variable is not explicitly initialized. This is not common in some other languages, but in Go, it ensures that all variables always have a valid initial value. Here are the zero values for each basic data type:
- The zero value for an integer is
0
- The zero value for a floating-point number is
0.0
- The zero value for a boolean is
false
- The zero value for a string is an empty string
""
For example:
var i int // Zero value is 0
var f float64 // Zero value is 0.0
var b bool // Zero value is false
var s string // Zero value is ""
Understanding the concept of zero values is very important, as it can help developers understand the behavior of variable initialization and can be used to prevent null pointer or uninitialized errors.
4. Scope of Variables
4.1 Local Variables
Local variables are variables defined within a function, and they can only be accessed within that function. Function parameters also belong to local variables. From the moment they are created, until the function execution is complete, local variables will disappear. Each time a function is called, local variables are recreated.
func localVariableExample() {
var localVariable int = 10 // This is a local variable
fmt.Println(localVariable)
}
func main() {
localVariableExample() // Output: 10
// fmt.Println(localVariable) // This will cause a compile error because localVariable is not visible here
}
In the example above, localVariable
can only be accessed within the localVariableExample
function.
4.2 Global Variables
Global variables are variables defined outside functions, and they can be accessed in any file within the same package. If you want to use global variables in other packages, the variable name must start with a capital letter, in accordance with Go's access control rules.
package main
import "fmt"
var globalVariable int = 20 // This is a global variable
func main() {
fmt.Println(globalVariable) // Output: 20
changeGlobal()
fmt.Println(globalVariable) // Output: 30
}
func changeGlobal() {
globalVariable = 30 // Change the value of the global variable
}
In this example, globalVariable
is visible in both the main
function and the changeGlobal
function.
5 Declaration and Use of Constants
5.1 The const
Keyword
We use the const
keyword to define constants. Constants are values that cannot be modified and once defined, their value cannot be changed. Constants can be of any basic data types such as integers, floating-point numbers, booleans, or strings.
const Pi = 3.14 // Declare a float constant
const StrConst string = "Hello, World!" // Declare a string constant
func main() {
fmt.Println(Pi)
fmt.Println(StrConst)
}
5.2 Enum Constants
The Go language does not have a specific enumeration type, but you can use the iota
keyword to achieve enumeration. Within a const
block, each additional constant declaration will increment the value of iota
by 1.
const (
Sunday = iota // 0
Monday // 1
Tuesday // 2
Wednesday // 3
Thursday // 4
Friday // 5
Saturday // 6
)
func main() {
fmt.Println(Sunday) // Output: 0
fmt.Println(Saturday) // Output: 6
}
The above code declares an enumeration for the days of the week, where iota
initializes at 0 within the const
block and increments by 1 for each subsequent declaration.
5.3 Scope of Constants
The scope of constants is similar to variables. If a constant is defined within a function, its scope is limited to that function. If a constant is defined outside a function (globally), its scope is the entire package, and if the first letter is capitalized, it can be accessed in other packages.
Managing the scope of constants helps reduce global scope pollution and improves program maintainability and readability.
const GlobalConst = "This is a global constant"
func main() {
const LocalConst = "This is a local constant"
fmt.Println(GlobalConst) // This is valid
fmt.Println(LocalConst) // This is valid
}
func anotherFunction() {
// fmt.Println(LocalConst) // This will cause a compilation error: LocalConst is not visible in this function
fmt.Println(GlobalConst) // This is valid
}
In this example, LocalConst
can only be accessed within the main
function, while GlobalConst
can be accessed throughout the entire package.