The concept, import and visibility of package in go

Source: Internet
Author: User
Tags uppercase letter
This is a creation in Article, where the information may have evolved or changed.

A package is a way of structuring code: Each program consists of the concept of a package (usually called pkg), which can use its own package or import content from other packages.

Like the concept of a class library or namespace in some other programming languages, each Go file belongs to and belongs to only one package. A package can consist of many .go source files as extensions, so the file name and package name are generally not the same.

You must indicate which package the file belongs to in the first line of the non-comment in the source file, such as: package main . package mainrepresents a program that can be executed independently, and each Go application contains a main package named.

An application can contain different packages, and even if you only use the main package, you do not have to write all of the code in a huge file: You can use some smaller files, and in the first line of each file non-comment, it is used package main to indicate that these files belong to the main package. If you intend to compile the package name not for the source file for main, for example pack1 , the resulting object file will be the executable program instead of the executable pack1.a . It is also important to note that all package names should use lowercase letters.

Standard library

The Go installation file contains a number of packages that can be used directly, namely the standard library. Under Windows, the standard library is located in a subdirectory under the Go root directory, pkg\windows_386 and under Linux, the standard library is in a subdirectory in the Go root directory (in the pkg\linux_amd64 directory if the installation is 32-bit linux_386 ). In general, standard packages are stored in the $GOROOT/pkg/$GOOS_$GOARCH/ directory.

Go's standard library contains a large number of packages (such as FMT and OS), but you can also create your own packages.

If you want to build a program, both the package and the files within the package must be compiled in the correct order. The dependencies of a package determine the order in which they are built.

Source files that belong to the same package must all be compiled together, and a package is a unit at compile time, so according to convention, each directory contains only one package.

If a package is changed or recompiled, all client programs that reference the package must be recompiled.

The package model in Go uses an explicit dependency mechanism for fast compilation purposes, and the compiler .o extracts the information of the transitive dependency type from the object file with the suffix name (required and only this file is needed).

If A.go dependent B.go , but B.go dependent on C.go :

    • Compile C.go , and B.go then yes A.go .
    • In order to compile A.go , the compiler reads B.o instead C.o .

This mechanism can significantly increase compilation speed when compiling large projects.

Each piece of code will only be compiled once

A Go program is a import keyword that links a set of packages together.

import "fmt"Tell the Go compiler that this program requires the use fmt of a package (function, or other element), which fmt implements the format IO (input/output) function. The package name is enclosed in a half-width double quotation mark "" . If you intend to import and load publicly declared methods from a compiled package, you do not need to insert the source code of the compiled package.

If more than one package is required, they can be imported separately:

"Fmt""Os"  

Or:

"Fmt" os" 

But there are shorter and more elegant methods (called factorization keywords, which also apply to the declarations or definitions of Const, VAR, and type):

Import (   "FMT"   "OS")   

It can even be in a shorter form, but will be forced to wrap after using gofmt:

Import ("FMT" OS")  

When you import multiple packages, the order in which they are imported is sorted alphabetically.

If the package name does . not / start with or begins, such as "fmt" or "container/list" , go looks in the global file, and if the package name ./ begins, go looks in the relative directory, and if the package name / begins with Windows Used in this way), it is found in the absolute path of the system.

Importing a package is equivalent to all the code objects that contain the package.

In addition to symbols _ , the identifiers of all code objects in the package must be unique to avoid name collisions. However, the same identifiers can be used in different packages because they can be distinguished by using the package name.

The package determines whether to expose its own code objects to external files through the following rules that are enforced by the compiler:

Visibility rules

When identifiers (including constants, variables, types, function names, structure fields, and so on) start with an uppercase letter, such as: Group1, an object using this form of identifier can be used by the code of the external package (the client program needs to import the package first), which is known as an export (as in object-oriented languages). public), identifiers are invisible to the package if they start with lowercase letters, but they are visible and available within the entire package (like private in an object-oriented language).

(Uppercase letters can use any Unicode-encoded character, such as Greek, not just the uppercase letter in ASCII code).

Therefore, after you import an external package, you can and will only be able to access the exported objects in the package.

Assuming that we have a variable or function in the package pack1 called Thing (which starts with T, so it can be exported), then the PACK1 package is imported into the current package, and Thing can be called with a dot tag like an object-oriented language: pack1.Thing (Pack1 is not omitted here).

So a package can also be used as a namespace to help avoid naming conflicts (name collisions): The difference between the same name variables in two packages is their package name, for example, pack1.Thing and pack2.Thing .

You can use the alias of the package to resolve the name conflict between package names, or to reset the package name according to your personal preference, such as: import fm "fmt" . The following code shows how to use the alias of a package:

Example 4.2 alias.go

Package main"FMT//ALIAS3Main () {FM.Println (" Hello, World")}    

Precautions

If you import a package and do not use it, you will throw an error when building the program, as imported and not used: os follows the motto of Go: "No unnecessary code!" “。

Hierarchical declaration and initialization of packages

You can import define or declare 0 or more constants (const), variables (Var), and types (type) after using the import package, and the scope of these objects is global (within the scope of this package), so you can be called by all functions in this package (such as Gotemplate.go C and V in the source file), and then declare one or more functions (func).

General structure of Go program

The following programs can be compiled smoothly but nothing is done, but this is a good way to show the preferred structure of a Go program. This structure is not mandatory, and the compiler does not care whether the main function is declared before or after the variable, but using a unified structure can have a better experience when reading go code from top to bottom.

All structures will be explained further in this chapter or in the following chapters, but the general idea is as follows:

    • After the import of the package is completed, the definitions or declarations of constants, variables, and types are started.
    • If the init function is present, the function is defined (this is a special function, and each package containing the function executes the function first).
    • If the current package is a main package, define the main function.
    • Then define the rest of the functions, first of all the methods of the type, followed by the main function in the order of successive calls to define the correlation function, if there are many functions, you can sort by alphabetical order.

Example 4.4 gotemplate.go

Package MainImport (The FMT")Const C ="C "var v int = 5 type t struct{}func init () {//initialization of Package}func main () {var a int func1 () //... fmt. Println (a)}func  (t t) method1 () {//...} func func1 () {//exported function Func1 //...}              

The Go program execution (program start) sequence is as follows:

    1. Import all other packages that are referenced by the main package sequentially, and then perform the following processes in each package:
    2. If the package imports another package, it executes recursively from the first step, but each package is imported only once.
    3. Constants and variables are then initialized in the reverse order in each package, and the function is called if it contains an init function.
    4. After doing this, main executes the same procedure, and finally calls the main function to start executing the program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.