The code organization structure of Go language is described in detail

  • 2020-05-05 11:22:12
  • OfStack

package (package)

A program is built as a package that can also use facilities provided by other packages.

An golang program is created by linking a set of packages.

A package can consist of multiple source files.

The names in the import package can be accessed through packagename.Itemname.

source file structure

golang each source file includes:

- an package phrase (which package the file belongs to); Its name will be the default name when the package is imported.


package fmt

- an optional import declaration set

import "fmt" // Use the default name
import myFmt "fmt" // Use the name myFmt

- 0 or more global or "package level" declarations.

single file package


package main // This file is the package main Part of the import "fmt" // This file USES packages "fmt" const hello = "Hello, The world \n" func main() {
fmt.Print(hello)
}

main and main.main

Each Go program contains a package called main and its main function. After initialization, the program starts from main. Similar to the main() function in C,C++.

The main.main function takes no arguments and returns no value. When main.main returns, the program exits immediately and returns success.

os package

The os package provides Exit functions as well as functions to access files I/O and command-line arguments.


// 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 and package scope

In a package, all global variables, functions, types, and constants are visible to all the code in the package.

For packages that import the package, only names starting with an uppercase letter are visible: global variables, functions, types, constants, and fields of global types and variables in methods and structures.


const hello = "you smell" // Can be seen in the package
const Hello = "you smell nice" // Global scope
const _Bye = "stinko!" // _ Not uppercase

This is very different from C/C++ : there is no extern, static, private and public.

initializes

There are two ways to initialize a global variable before main.main executes:

1) global declaration
with initialization statements 2) inside the init function, there may be an init function in each source file.

Package dependencies ensure the correct order of execution.

Initialization is always single-threaded.

Initialization example:


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 build

To build a program, the package and the files in 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 one package, ignore the tests,


cd mypackage
6g *.go

Typically, we use make; Go language specific tools are coming soon.

builds the fmt package


% 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 target file is placed in the _obj subdirectory.

Makefiles is usually written with the help provided by Make.pkg. Look at the source code.

test

To test a package, write a set of Go source files in the package. Name these files * _test.go.

In these files, global functions with names starting with Test[^ a-z] are automatically executed by the test tool gotest. These functions should be signed with the following function:


func TestXxx(t *testing.T)

The testing package provides support for logging, benchmarking, error reporting, and more.

a test example

An interesting code from fmt_test.go:


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 gotest tool go test command


% 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
%

A test example of benchmark

The function signature of Benchmark is as follows:


func BenchmarkXxxx(b *testing.B)

b.N times; The rest is done by the testing package.

Here is an example of benchmark from fmt_test.go:


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


% 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 package.

The current library is modest, but growing.

Some examples:

Package                           example
fmt                                  
os                 Read, Write
strconv                 numbers < - > strings                   Atoi, Atof, Itoa
io                                     Copy Pipe
flag                   flags             Bool, String
log                     event log                           regexp                                 template           html                     Parse, Execute
bytes                          

more about fmt

The fmt package contains some familiar names:


Printf � Print to standard output
Sprintf � Returns a string
Fprintf � writes os.Stderr Etc.

There are


Print, Sprint, Fprint � plain no format
Println, Sprintln, Fprintln � No format, but with Spaces in the middle and at the end \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 documentation

Comments are included in the source code.

Comments can be extracted from the command line or the web tool.

Link: http: / / golang org/pkg/

Command:


% godoc fmt
% godoc fmt Printf


Related articles: