Package (Package)
A program is built in the form of a package that can also use some of the facilities provided by other packages.
A Golang program is created by linking a set of packages.
A package can consist of multiple source files.
The name in the import package can be passed through PackageName. ItemName access.
source file Structure
Golang each source file includes:
-a package sentence (which package the file belongs to); its name will be the default name when the package is imported.
Copy Code code as follows:
-An optional import declaration set
Copy Code code as follows:
Import "FMT"//Use default name
Import myfmt "FMT"//Use name MYFMT
-0 or more global or "package level" declarations.
Single File Package
Copy Code code as follows:
Package main//This file is part of the package main
Import "FMT"//This file uses the package "FMT"
const Hello = "Hello, world \ n"
Func Main () {
Fmt. Print (Hello)
}
Main and Main.main
Each Go program contains a package named Main and its main function, which is executed from main after initialization. Similar to the main () function in c,c++.
The Main.main function has no arguments and no return value. When Main.main returns, the program exits immediately and returns to success.
OS Packs
The OS package provides the Exit function, as well as functions to access file I/O and command line arguments.
Copy Code code as follows:
A version of Echo (1)
Package Main
Import (
"FMT"
"OS"
)
Func Main () {
If Len (OS. Args) < 2 {//Length of argument slice
Os. Exit (1)
}
For i: = 1; I < len (OS. Args); i++ {
Fmt. Printf ("Arg%d:%s\n", I, OS.) Args[i])
}
}//falling off end = = OS. Exit (0)
Global scope and Package scope
In a package, all global variables, functions, types, and constants are visible to all code for the package.
For packages that import the package, only names that start with uppercase letters are visible: global variables, functions, types, constants, and fields of global types and variables in methods and structures.
Copy Code code as follows:
Const Hello = "you smell"//package visible
Const Hello = "smell nice"/global visible
Const _bye = "Stinko!"//_ Not uppercase
This is a very different from C + +: There is no extern, static, private, or public.
Class
There are two ways to initialize a global variable before Main.main execution:
1 Global declaration with initialization statement
2 within the INIT function, there may be an init function in each source file.
Package dependencies guarantee the correct order of execution.
Initialization is always single-threaded.
Initialization example:
Copy Code code as follows:
Package Transcendental
Import "Math"
var Pi float64
Func init () {
Pi = 4*math. Atan (1)//init function computes Pi
}
Package Main
Import (
"FMT"
"Transcendental"
)
var Twopi = 2*transcendental. Pi//Decl computes Twopi
Func Main () {
Fmt. Printf ("2*pi =%g\n", Twopi)
}
Output: 2*pi = 6.283185307179586
Package and program Building
To build a program, the package and the files within it must be compiled in the correct order. Package dependencies determine the order in which packages are built.
Within a package, the source files must be compiled together. Packages are compiled as a unit, by convention, each directory contains a package, ignoring the test,
Copy Code code as follows:
Usually, we use make; The Go Language Special tool will soon be released (go 1 can be directly used in the go builds, go install and other advanced commands, can no longer directly with the 6g, 6l and other commands. )
Building FMT Packages
Copy Code code as follows:
% pwd
/users/r/go/src/pkg/fmt
% ls
Makefile fmt_test.go format.go print.go # ...
% make # Hand-written but trivial
% ls
Makefile _go_.6 _obj fmt_test.go format.go print.go # ...
% make clean; Make
...
The destination file is placed in the _obj subdirectory.
The Help that MAKE.PKG provides is usually used when writing makefiles. Look at the source.
Test
To test a package, you can write a set of Go source files in the package; name the files *_test.go.
In these files, global functions that begin with the name Test[^a-z] are automatically executed by the test tool gotest, and these functions should be signed with the following function:
Copy Code code as follows:
Func testxxx (t *testing. T
The testing package provides support for logs, benchmarking, error Reporting, and so on.
A test example
Excerpt from an interesting piece of code in FMT_TEST.GO:
Copy Code code as follows:
Import (
"Testing"
)
Func testflagparser (t *testing. T) {
var flagprinter flagprinter
For I: = 0; I < Len (flagtests); i++ {
TT: = Flagtests[i]
S: = Sprintf (tt.in, &flagprinter)
If s!= tt.out {
Method call coming up–obvious syntax.
T.errorf ("Sprintf (%q, &flagprinter) =>%q," + "want%q", tt.in, S, tt.out)
}
}
}
Gotest (in Go 1, gotest tools are replaced with the Go Test command)
Copy Code code as follows:
% ls
Makefile fmt.a fmt_test.go format.go print.go # ...
% Gotest # By default, does all *_test.go
Pass
wally=% gotest-v Fmt_test.go
= = = RUN FMT. Testflagparser
-pass:fmt. Testflagparser (0.00 seconds)
= = = RUN FMT. Testarrayprinter
-pass:fmt. Testarrayprinter (0.00 seconds)
= = = RUN FMT. Testfmtinterface
-pass:fmt. Testfmtinterface (0.00 seconds)
= = = RUN FMT. Teststructprinter
-pass:fmt. Teststructprinter (0.00 seconds)
= = = RUN FMT. testsprintf
-pass:fmt. Testsprintf (0.00 seconds) # plus lots more
Pass
%
An example of a benchmark test
The benchmark function signature is as follows:
Copy Code code as follows:
Func benchmarkxxxx (b *testing. B
and is recycled to execute B. n times; the rest is done by the testing package.
Here's a benchmark example from Fmt_test.go:
Copy Code code as follows:
Package FMT//package is FMT, not main
Import (
"Testing"
)
Func Benchmarksprintfint (b *testing. B) {
For I: = 0; i < B.N; i++ {
Sprintf ("%d", 5)
}
}
Benchmarking:gotest
Copy Code code as follows:
% gotest-bench= "." # Regular expression identifies which
Fmt_test. Benchmarksprintfempty 5000000
310 ns/op
Fmt_test. Benchmarksprintfstring 2000000
774 Ns/op
Fmt_test. Benchmarksprintfint
5000000
663 Ns/op
Fmt_test. Benchmarksprintfintint 2000000
969 Ns/op
...
%
Library
A library is a bag.
The current size of the library is modest, but it is still growing.
Some examples:
Examples of Bao
FMT format I/O Printf, Scanf
OS OS interface Open, Read, Write
StrConv numbers<-> Strings Atoi, Atof, itoa
IO general I/O Copy, Pipe
Flag Flags:–help etc Bool, String
Log event logs Logger, Printf
RegExp Regular Expression Compile, Match
Template html etc Parse, Execute
Bytes byte array Compare, Buffer
More about FMT
The FMT package contains some familiar names:
Copy Code code as follows:
printf– Print to standard output
sprintf– returns a string
fprintf– writes to the OS. STDERR, etc.
And also
Copy Code code as follows:
Print, Sprint, fprint– unformatted no format
Println, Sprintln, fprintln– unformatted, but add in the middle of the space, the end of the join \ n
Fmt. Printf ("%d%d%g\n", 1, 2, 3.5)
Fmt. Print (1, "", 2, "", 3.5, "\ n")
Fmt. Println (1, 2, 3.5)
Each output the same result: "1 2 3.5\n"
Library Document
The source code contains comments.
The command line or Web tool can extract the annotations.
Link: http://golang.org/pkg/
Command:
Copy Code code as follows:
% Godoc FMT
% Godoc FMT Printf