1. File name, keyword and identifier
1.1. Name and identifier
Source files in Go are usually.go
is an extension and stored on the computer. The naming of these files is entirely composed of lowercase letters, for example. Underscore is usually used for file names containing multiple words
_
to connect various parts, such asscanner_test.go
, and the file name will not contain spaces or other special characters.
In Go environments, there is no limit on the size of the source file, and a file can contain code from several lines to thousands of lines.
In Go code, almost all elements need names or identifiers, and these identifiers are case sensitive, similar to C-series languages. Valid identifiers should be underlined in letters (supports any UTF-8 encoded characters) or underscore_
Start with any number of letters, numbers or underscores, for example:X56
、group1
、_x23
、i
、өԑ12
。
However, some identifiers are invalid, including:
-
1ab
: It is not allowed to start with a number. -
case
: Because it is a keyword in Go language. -
a+b
: Contains operators, which are not allowed.
In particular, underline_
called a blank identifier, it has special uses in the Go language. Any type of value can be assigned to it, but the result after the assignment will not be used, and further variable assignment or calculation cannot be performed through it.
Also, in Go code, sometimes you will encounter variables, types, or methods that don't have explicit names, which are often called anonymous variables. Using anonymous variables can improve code flexibility in some scenarios, although they are not a necessary element to writing Go programs.
1.2. Keywords
The Go language defines 25 keywords or reserved words that have special semantics when writing Go code and cannot be used as identifiers. These keywords cover multiple aspects such as control structure, data type definition, and package management. Here is a list of all keywords in Go:
Control flow keywords:
-
break
: Used to interrupt the current loop; -
case
: existswitch
In a statement, it is used to define a branch; -
continue
: Skip the remaining part of the current loop and continue to execute the next loop; -
default
: existswitch
orselect
In a statement, define the default branch; -
defer
: Delay execution of a function until the execution of the function containing it ends; -
else
: andif
Use together to define a block of code that is executed when the condition is not met; -
fallthrough
: existswitch
Enforce the next onecase
; -
for
: Define loops; -
goto
: Jump to the specified tag; -
if
: Conditional statement; -
return
: Return value from function; -
select
: Used to handle reception operations of multiple channels; -
switch
: Conditional branch statement;
Data type and structure keywords:
-
chan
: Used to define channel type; -
const
: Define constants; -
func
: Define the function; -
interface
: Define the interface; -
map
: Define the mapping type; -
package
: Define the package name; -
range
: Used to iterate over arrays, slices, strings, maps or channels; -
struct
: Define structure; -
type
: Define a new type; -
var
: Define variables.
These keywords are fundamental components of the Go language, and understanding their uses and semantics is essential for writing effective and efficient Go programs.
The reason why we deliberately keep so few keywords in Go code is to simplify the code parsing in the first step of the compilation process. Like other languages, keywords cannot be used as identifiers.
In addition to 25 keywords, Go provides 36 predefined identifiers, including a series of basic data types names and some important built-in functions. These predefined identifiers are part of the Go language standard library and provide the ability to operate basic data types and perform critical operations.
Here are 36 predefined identifiers in Go:append
、bool
、byte
、cap
、close
、complex
、complex64
、complex128
、copy
、false
、float32
、float64
、imag
、int
、int8
、int16
、int32
、int64
、iota
、len
、make
、new
、nil
、panic
、print
、println
、real
、recover
、string
、true
、uint
、uint8
、uint16
、uint32
、uint64
、uintptr
。
1.3. Symbols
Programs are generally composed of keywords, constants, variables, operators, types and functions.
These delimiters may be used in the program: brackets()
, brackets[]
and braces{}
。
These punctuation marks may be used in the program:.
、,
、;
、:
and…
。
The code of the program is structured through statements. Each statement does not need to be semicolons like other languages in the C family;
End, because all these tasks will be done automatically by the Go compiler.
If you plan to write multiple statements on the same line, they must use;
Artificial distinction, but in actual development we do not encourage this practice.
2. Go package
2.1. The concept of Go language pack
Packages are used in the Go language for structured code, similar to class libraries or namespaces in other programming languages. Each Go source file belongs to a specific package, and a package can be composed of multiple.go
Composition of source files with extensions. Normally, the file name and the package name are different.
On the first line of the non-commentation of the source file, it is necessary to specify which package the file belongs to, e.g.package main
。package main
Defines a program that can be executed independently, and each Go application must contain a name calledmain
bag.
Although an application may contain multiple different packages, even if onlymain
Package, you don't have to write all the code in a huge file. The code can be scattered into several smaller files, using the first line of each filepackage main
It means they all belongmain
Bag. If the compiled package name is notmain
,likepack1
, then the compilation producesObject files instead of executable programs. It is worth noting that all package names should use lowercase letters.
2.2. Standard library for Go language
The Go language installation package includes a rich standard library, which is a set of pre-compiled packages that can be used directly in your program. The specific location of the standard library depends on the operating system and processor architecture.
For example, on Windows systems, the standard library is located in the root directory of the Go installationpkg\windows_386
In subdirectory; on Linux system, if it is 64 bit, thenpkg\linux_amd64
In the subdirectory, the 32-bit system islinux_386
in the directory. Normally, standard inventory is placed in$GOROOT/pkg/$GOOS_$GOARCH/
In the directory.
The standard library contains many practical packages, such asfmt
andos
. In addition to using these ready-made packages, you can also create your own packages to meet specific functional needs.
In order to build a program, all relevant packages and files must be compiled in the correct order, which is usually determined by the dependencies of the packages. In Go, all source files belonging to the same package must be compiled together, because a package is considered a separate compilation unit at compile time. By convention, each directory usually contains only one package to keep the structure clear and manageable.
2.3. Go language pack dependency and compilation strategy
In the Go package model, after a package is changed or recompiled, all client programs that reference the package must be recompiled to ensure that all dependencies are up to date. Go's compiler uses an explicit dependency mechanism that greatly speeds up compilation.
During the compilation process, the Go compiler has the suffix name as.o
Extract information about the transitive dependency type from the object file. This means that when the compiler compiles a file, it only needs to reference the directly dependent.o
Files, not all relevant source files. For example:
- Suppose there are three files:
、
and
,in
Depend on
,and
Depend on
。
- Compilation order should be compiled first
, compile again
, finally compile
。
- Compiling
When the compiler only needs to read
document. although
Dependence
, compile
Not directly needed
, because all the necessary information is already in
middle.
This compilation mechanism not only simplifies dependency management, but also makes compiling large projects more efficient. In this way, Go language can provide fast compilation speeds while keeping the code modular and highly organized.
2.4. Each piece of code will only be compiled once.
A Go program is throughimport
Keywords link a set of packages together.
import "fmt"
Tell the Go compiler that this program needs to be usedfmt
package (function, or other element),fmt
The package implements a function that formats IO (input/output). The package name is enclosed in half-width double quotes""
middle. If you plan to import and load publicly declared methods from compiled packages, you do not need to insert the source code of the compiled packages.
If multiple packages are needed, they can be imported separately:
import "fmt" import "os"
or:
import "fmt"; import "os"
But there are shorter and more elegant methods (called factorization keywords, which are also suitable forconst
、var
andtype
Declaration or definition of ):
import ( "fmt" "os" )
It can even be shorter, but will be forced to wrap the line after using gofmt:
import ("fmt"; "os")
When you import multiple packages, it is best to arrange the package names alphabetically, so that it is clearer and easier to read.
If the package name is not.
or/
The beginning, such as"fmt"
or"container/list"
, Go will search in the global file; if the package name is./
At the beginning, Go will be searched in the relative directory; if the package name is/
At the beginning (it can also be used in Windows) it will be searched in the absolute path of the system.
Importing a package is equivalent to all code objects containing this package.
Except for symbols_
, the identifiers of all code objects in the package must be unique to avoid name conflicts. But the same identifier can be used in different packages, because the package name can be used to distinguish them.
The package decides whether to expose its own code objects to external files through the following rules enforced by the compiler:
2.5. Identifier visibility and package management of Go language
In Go, the first case of an identifier (including constants, variables, types, function names, structure fields, etc.) determines its visibility and accessibility. If the identifier begins with capital letters (such asGroup1
), then the object of this identifier can be accessed by external packages, which is equivalent to the in other object-oriented languagespublic
. This mechanism is called export. It is worth noting that capital letters can be any Unicode-encoded character, not limited to ASCII code.
Conversely, if the identifier starts with a lowercase letter, it is invisible to outside the package, similar to the one in an object-oriented languageprivate
. This identifier is only visible and available inside the package to which it belongs.
For example, suppose it is in the packagepack1
There is a variable or function in it calledThing
(in capitalT
Beginning, so it can be exported), imported in other packagespack1
Available to accessThing
, the usage method is as follows:. Here,
pack1
As a namespace, it cannot be omitted.
This namespace feature of the package helps avoid name conflicts. For example,and
It can clearly distinguish variables or functions of the same name belonging to different packages.
2.6. Use the alias of the package
In Go, you can resolve package name conflicts or simplify your code by specifying an alias for packages. For example, you can import it like thisfmt
Package and set alias for it:
package main import fm "fmt" func main() { ("hello, world") }
2.7. Package declaration and initialization
In Go, you can define or declare constants at the package level after importing the package (const
),variable(var
) and type (type
). The scope of these definitions is global and can be accessed throughout the package. After that, one or more functions can be declared (func
) to perform specific logical operations. This structure makes the code clear and manageable.
Ps: If you import a package but don't use it in your code, the Go compiler will throw an error, for exampleimported and not used: os
. This reflects Go’s philosophy of design: “No unnecessary code!”
Summarize
This is the article about Go file names, identifiers, keywords and packages. For more related Go file names, identifiers, keywords and package content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!