Go language core Beauty 1.4-packages and files

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

I. Package

The package in the go language, like the library or module in other languages, supports modularity, encapsulation, reusability, and individual compilation. The source of the package consists of several. go files, where the directory name is the last word of the import path, for example, all files for the Github.com/sunface/corego package are stored under $gopath/src/github.com/sunface/corego.


Each package has a separate namespace. For example, the decode in decode and UNICODE/UTF16 in the image package is a completely different function. If you want to reference a function of a third-party library, we will use the package. The form of func, such as image. Decode and Utf16.decode.


The package also allows us to control the visibility of variables and functions within the package itself. In the go language, the export of variables, functions, etc. depends only on one factor: the case of the first letter.


Imagine what we would do if our temperature conversion software became popular and wanted to contribute to the open source community.

First Let's create a package github.com/sunface/temconv, and make some changes based on the example in Section 1.3. This package contains two files that demonstrate how to separate data declarations from data access, and in real-world projects, this package actually requires only one file.

Temconv.go contains type declarations, constants, types of method:

Package Tempconvimport "FMT" type Celsius float64type Fahrenheit float64const (    absolutezeroc Celsius = -273.15    FREEZINGC     Celsius = 0    boilingc      Celsius = +) func (c Celsius) string () string    {return FMT. Sprintf ("%g°c", C)}func (f Fahrenheit) string () string {return FMT. Sprintf ("%g°f", F)}

Conv.go contains the conversion function:

The temperature conversion package tempconv//converts the Celsius temperature to Fahrenheitfunc Ctof (c Celsius) Fahrenheit {return Fahrenheit (C*9/5 + 32)}//will Fahre Nheit temperature conversion to Celsius.func FToC (f Fahrenheit) Celsius {return Celsius ((f-32) * 5/9)}

The first line of each. Go file is a declaration of the package Tempconv that indicates which packet the file belongs to. When the package is imported, you can call its members like this: Tempconv. Ctof and so on. Package-level variables, such as types, constants, and so on, are visible to all files within the same package, as if all code is defined in the same file. Note that Temconv.go has been imported into FMT here. But Conv.go did not, because it did not use any members of the FMT.

The const variable at the package level in the above code, which starts with an uppercase letter, can be used outside of the Temconv package, Tempconv. Absolutezeroc:

Fmt. Println (Tempconv. Ctof (Tempconv. BOILINGC))//"212°f"


We will select one of the. go files in the package to make package-level comments, which are written before the packages declaration of the file (see previous conv.go). In general, the annotations here are an overview of the file. A package has only one file that requires a package-level comment. These annotations are typically placed in the Doc.go file and can be viewed later through the Go Doc tempconv.


Second, package imports (import)

In the Go program, each package is marked with a unique string, called the import path, which is imported uniformly in the import declaration. The Go language specification does not make any conventions on the imported package names, which are parsed by go tools. When using the Go tool, an import path represents a folder that contains the. go file that makes up the package.

In the import declaration, each package has its own import package name, which, by convention, is the last word in the import path, such as Github.com/sunface/tempconv's import package name is Temconv:

Package Mainimport (    "FMT"    "OS" "StrConv" "    Github.com/sunface/tempconv") func main () {    for _, arg : = Range OS. Args[1:] {        T, err: = StrConv. Parsefloat (ARG, +)        if err! = Nil {            FMT. fprintf (OS. Stderr, "CF:%v\n", err)            OS. Exit (1)        }        F: = Tempconv. Fahrenheit (t)        c: = Tempconv. Celsius (t)        FMT. Printf ("%s =%s,%s =%s\n",            F, Tempconv. FToC (f), C, Tempconv. Ctof (c))    }}
Tempconv can therefore be called directly. Ctof. You can also use the alias mechanism to avoid package name collisions:
Import ("Github.com/sunface/tempconv" temp "github.com/sunfei/tempconv")
Call Github.com/sunfei/tempconv:temp. Ctof; Call Github.com/sunface/tempconv:tempconv. Ctof.

The above program converts individual numeric command-line arguments to Celsius and fahrenhit values.

$ go Build github.com/sunface/corego/ch1.4/cf$./cf 3232°f = 0°c, 32°c = 89.6°f$./CF 212212°f = 100°c, 212°c = 413.6°f$. /cf-40-40°f =-40°c,-40°c = -40°f

If you import a package and do not use it, then the compilation error will be reported, the compiler's check can help eliminate unnecessary package references, although during debug may be compared to the egg pain, such as commenting out the log. Print ("Hello") may eliminate the program's reference to the log package, which will cause the compiler to error. Fortunately, we can use the Golang.org/x/tools/cmd/goimports tool, which automatically inserts and removes package references, and most IDES support configuration to use Goimports.



Three, the initialization of the package

Package-level variables are initialized in the order in which they are initialized, unless there is a dependency order between the variables:

var a = B + C     //A third initialization 3var B = f ()       //b second initialization, call Fvar c = 1         //C First initialize func f () int {return c + 1}
If a package has more than one. Go file, the files are initialized in the order that they are submitted to the compiler, and the Go tool sorts the. go file by file name before waking the compiler.

Any file can contain any number of init functions:

Func init () {/* ... */}
This init function cannot be called or referenced, and within each file, the Init function automatically runs when the program starts, and each init function in the file executes sequentially in the order in which it is declared.



Each package will only be initialized once, first of all to initialize the dependency package, if the package P imports Q, it is certain that Q will be fully initialized before P is initialized. Because the dependency package is initialized first, the initialization of the program is bottom-up, and the main package is definitely the last initialization (the package is organized like a tree structure, and main is the root node). This will initialize all packages at the beginning of the main function!




Article ownership: Golang Contact: Sun Fei, cto@188.com!

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.