This is a creation in Article, where the information may have evolved or changed.
Original reproduced http://www.cnblogs.com/happyframework/p/3322292.html
Go: How to Organize your code
Working space (Workspaces)
Go code must be kept in a workspace,workspace is a directory structure, he has three subdirectories composed of:
- SRC: Contains the source code that makes up the packages, and a directory is a package.
- PKG: Contains the package objects (compiled class library).
- Bin: Contains the executable commands (the compiled executable program).
The Go tool compiles the packages, and then installs the compiled results into the PKG directory or bin directory, following a wet example:
Gopath Environment variables
The GOPATH environment variable points to the location of the workspace, if not set, go to set it yourself, or go install will fail.
Package path
The packages of a standard class library can use short names, such as FMT. For your own packages, it's best to provide a base path, which avoids naming conflicts, and here's my naming principle:
1 happygo.codeplex.com/study (source code service provider warehouse/project).
Your first program
Select a package path
1 Happygo.codeplex.com/study/hello
Hello.go
The package main//command executable (command-line executable) must use main as the packages name.
Import "FMT"
Func Main () {
Fmt. Print ("Hello, world! \ n ")
}
Project structure
Your first class library
Select a package path
1 happygo.codeplex.com/study/hellolib
Hellolib.go
Package Hellolibfunc Max (x int, y int) int {if x >= y {return x} return y}
Modify Hello.go, call class Library
Package Mainimport ("FMT" "Happygo.codeplex.com/study/hellolib") func main () {FMT. Print ("Hello, world! \ n ") fmt. Printf ("The largest of the 2 and 3 is%d! ", Hellolib. Max (2, 3)}
Project structure
Note: Go uses a static link (the code that is dependent is linked to a file).
Pack name (package name)
The go source file must start with the package declaration:
1 Package name
Some rules:
- All files in one package (file) must use the same name.
- Go Language Convention the last element of the import path is the package name.
- Executable commands must use package main.
Test integration
Go provides the Go Test command and the testing package to help us do the testing, the following are the organization rules for testing:
- The file must end with _test.go.
- The function name must contain the following signature: Func testxxx (t *testing. T).
Hellolib_test.go
Package Hellolib
Import "Testing"
Func Testmax (t *testing. T) {
Const x, y = 2, 3
Max: = max (x, y)
If max = = x {
T.error ("Max Error! ")
}
}