Preface
Go language, as a modern programming language, has won the favor of developers for its simplicity and efficiency. In Go language, constants and variables play a crucial role as basic elements in storing and manipulating data. By correctly understanding and using constants and variables, developers can write more robust and efficient code. This article will introduce in detail the definitions, usage specifications, and common application scenarios of constants and variables in the Go language, helping developers better grasp these core concepts.
1. Constants and enums in Go language
In Go language, constants are a useconst
Immutable value of keyword definition. Constants can be Boolean, numeric (integer, floating point, complex) and string. Once these values are set, they cannot be modified during the program run.
1.1. Definition of constants
The definition format of constants isconst identifier [type] = value
. Type declarations can be omitted because the Go compiler can automatically infer the type of a constant based on the assignment.
Example:
const Pi = 3.14159 // Type is inferred as float64const b string = "abc" // explicitly declare type stringconst b = "abc" // Implicit type, inferred as string
1.2. Constant calculation rules
The value of a constant must be determined at compile time, so any operation involving runtime calculations cannot be used for the definition of a constant. Built-in functions (such aslen()
) can be used in constant expressions, but custom functions cannot.
Example:
const c1 = 2/3 // Correct, can be sure when compilingconst c2 = getNumber() // Error, getNumber() is the value calculated at runtime
1.3. Digital constants
Digital constants are very flexible in Go, they have no fixed size or symbols and can be used as needed. The accuracy of the digital constants is very high and there is no overflow.
Example:
const Ln2 = 0.693147180559945309417232121458176568075500134360255254120680009 const Log2E = 1/Ln2 // Accurate calculationconst Billion = 1e9 // Floating point constantsconst hardEight = (1 << 100) >> 97 // Bit operation generates constants
1.4. Parallel assignment and enumeration
Go supports declaring multiple constants using parallel assignments, which is especially useful when defining enumerations.
Example:
const ( Monday, Tuesday, Wednesday, Thursday, Friday, Saturday = 1, 2, 3, 4, 5, 6 ) const ( Unknown = 0 Female = 1 Male = 2 )
1.5. iota enumerator
iota
is a special constant generator for Go, mainly used to create incremental enum values. In oneconst
In the declaration block, every new row of constant declaration is added.iota
The value of will automatically increase by 1.
Example:
const ( a = iota // a = 0 b // b = 1 c // c = 2 ) const ( _ = iota // Ignore the first value KB = 1 << (10 * iota) // 1024 MB // 1048576 )
iota
It can also be used for more complex expressions, such as combining bit operators to represent the state of a resource.
In general, in Go, constants provide a safe and efficient way to process invariant data. By using constants, runtime errors can be reduced and program performance can be improved. Use correctlyconst
andiota
It can greatly enhance the readability and maintenance of the code.
2. Variables in Go language
2.1. Introduction to variables
In Go language, variable declarations are generally usedvar
Keywords, followvar identifier type
form. Unlike many programming languages, Go puts the variable type behind the variable name when declaring variables. This design is intended to avoid declaring forms similar to those that may cause confusion in C (for example:int* a, b;
Herea
It is a pointer andb
no). In Go, declaring two pointer variables is more intuitive:
var a, b *int
This syntax structure helps read code sequentially from left to right, making the code easier to understand and maintain.
Example:
var a int var b bool var str string
Or use the form of factorization keywords to declare:
var ( a int b bool str string )
This format is often used to declare global variables. After declaration, the Go system will automatically initialize the variable to a zero value of its type, for example:int
The zero value is0
,float32/64
for0.0
,bool
forfalse
,string
is an empty string, and the pointer isnil
。
The naming of variables follows the camel nomenclature, for examplenumShips
andstartDate
. If global variables need to be used by external packages, the initial letter must be capitalized.
The scope of a variable depends on the location of the declaration. Global variables (declared in the function in vitro) can be used throughout the package or even in external packages. Local variables are only valid in the body of the function that declares them.
2.2. Value type and reference type
Value type (such asint
、float
、bool
andstring
) variables directly store the value itself, and the place where the value is stored in memory points directly to the value:
var i int = 42 j := i // Copy the value of i to j
Revisej
It will not affecti
. The variables of reference types (such as slices, maps, channels, and pointers) store a reference to the memory address. Assigning and passing a variable of reference type will copy its reference instead of its data itself.
2.3. Print
Go providesfmt
Package is used to format output, wherePrintf
Functions can output formatted strings to the console:
("The operating system is: %s\n", )
Format strings support various placeholders, allowing precise control of the output format.
2.4. Short form, use:=
Assignment operator
Inside the function, a short declaration statement can be used.:=
To initialize the variable:
a := 1 b := false
This form is concise and allows the compiler to automatically infer the type of variables. This syntax can only be used within functions and is not applicable to declarations of global variables.
2.5. Example
2.5.1 Example 1: local_scope.go
This example shows how to handle local and global variables in a Go program. Here is the code for the program:
package main var a = "G" func main() { n() m() n() } func n() { print(a) } func m() { a := "O" print(a) }
In this example, you will see the global variablea
How to use local variablesa
Interact in different functions.n()
in the functiona
Directly refer to global variables, andm()
Ina
is a local variable, only inm()
The function is valid internally.
2.5.2 Example 2: global_scope.go
This example is used to show how global variables are shared among functions. Here is the complete code:
package main var a = "G" func main() { n() m() n() } func n() { print(a) } func m() { a = "O" print(a) }
In this program,a
is a global variable. existm()
The function is in the righta
The changes made will affect subsequent pairsa
Visits, including inn()
The function is in the righta
Recitation of .
These two examples effectively reveal the behavior of variables in different scopes, emphasizing the difference between local and global variables in Go and how they affect each other. In this way, developers can better understand and master the scope and life cycle of variables in complex programs.
Attachment: Go declares a variable with a multi-line string
How to declare a multi-line string variable? Use ` to include it.
package main import ( "fmt" ) func main() { str := `hello world v2.0` (str) }
Summarize
This is the article about the definition, usage specifications and common application scenarios of constants and variables in Go. For more relevant content on the use of constants and variables in Go, please search for my previous articles or continue browsing the related articles below. I hope you can support me in the future!