In engineering development projects, Go language source reuse is based on packages.

Package is a collection of multiple Go source codes, which is a high-level code reuse scheme. Go language provides many built-in packages, such as FMT, OS, IO, etc.

The definition of package

The SRC directory organizes and holds the Go source files as code packages. Each code package corresponds to a folder in the SRC directory. Each subdirectory is a code package.

The code package name and file directory name are not required to be the same. For example, the file directory is called server, but the code package name can be declared as “main”, but the source file in the same directory in the first line of the declaration of the package, must be the same!

You can also create your own packages based on your needs. A package can simply be thought of as a folder that holds. Go files. All go files under this folder add the following code to the first line of the code to declare the package that the file belongs to.

packageThe package nameCopy the code

Matters needing attention:

  • Files directly under a folder can belong to only one folderpackage, the same onepackageFiles cannot be in more than one folder.
  • The package name cannot be the same as the folder name-Symbols.
  • Package is calledmainPackage is the entry package for the application, which is compiled to produce an executable file that is not compiledmainThe package source code does not get an executable.
  • Files under the same package belong to the same project fileimportPackage, can be used directly

visibility

If you want to reference an identifier (such as a variable, constant, type, function, etc.) in a package from another package, the identifier must be visible to the public. To make an identifier visible in the Go language, simply capitalize the first letter of the identifier:

package pkg

import "fmt"

// Package variable visibility

var a = 100 // The external package is invisible and can only be used within the current package

// The outer package is visible and can be used in other packages
const Mode = 1

type person struct { // The external package is invisible and can only be used within the current package
	name string
}

// The outer package is visible and can be used in other packages
func Add(x, y int) int {
	return x + y
}

func age(a) { // The external package is invisible and can only be used within the current package
	var Age = 18 // Function local variables, external packages are not visible, can only be used within the current function
	fmt.Println(Age)
}
Copy the code

Field names in structures and method names in interfaces can be accessed by external packages if the first letter is uppercase:

type Student struct {
	Name  string // Methods that can be accessed outside the package
	class string // Only fields accessible within packages
}

type Payer interface {
	init() // A package-only access method
	Pay()  // Methods that can be accessed outside the package
}
Copy the code

The main package

Go’s main() package is called main. If the main package wants to reference other code, you need to import it!

Package import

To reference the contents of other packages in your code, import the packages you use using the import keyword. The syntax is as follows:

A: Usually import

// Single import
import "package"
// Batch import
import (
  "package1"
  "package2"
  )
Copy the code

B: Click on the operation sometimes see the following way to import packages

import(."fmt"
) 
Copy the code

So what this dot operation means is that after the package is imported when you call the package function, you can omit the prefix of the package name, which is fmt.println (“hello world”) you can omit it and write Println(“hello world”)

Matters needing attention:

  • Import import statements are usually placed below the package declaration statement at the beginning of a file.
  • The imported package name needs to be enclosed in double quotation marks.
  • The package name from$GOPATH/src/After the start of the calculation, use/Separate paths.
  • Cyclic package import is prohibited in Go.

Custom package name

Custom package name As the name implies you can name a package with another name that is easy to remember. When importing, you can define an alias for the package.

import (
  p1 "package1"
  p2 "package2"
  )
// When used: alias operation, prefix becomes custom prefix when calling package function
p1.Method()
Copy the code

Anonymous import package

If you only need to perform initialization operations when importing packages, you do not need to use other functions, constants, and other resources in the package. You can import packages anonymously when importing them.

This operator is often confusing to many people:

import (
   "database/sql"
   _ "github.com/mysql/driver"
 ) 
Copy the code

The _ operation actually imports the package, and instead of using the package’s function directly, calls the package’s init function. That is, using underscores as aliases for packages simply executes init().

The path name of the imported package can be a relative path or an absolute path. The absolute path (starting from the project root directory) is recommended.

Anonymously imported packages are compiled into the executable just like any other imported package.

The init () function

Introduction to the init() function

The package import statement automatically triggers the call to the init() function inside the package during the Go program execution. Note that the init() function takes no arguments and returns no value. The init() function is called automatically when the program is running and cannot be called actively from within the code. The code in init() is executed before the main() function is executed to initialize the specific resources required by the package.

The sequence of package initialization is shown below:

Order in which the init() function is executed

The Go package checks all packages it imports, starting with the main package, and each package may import other packages. The Go compiler builds a tree of package references, and then compiles the package code based on the order of references.

At run time, the last package to be imported is the first to initialize and call its init() function, as shown below:

Disallow cyclic reference packages: A -> B -> C -> A

The similarities and differences between init and main

Similarities:

  • Two functions cannot be defined with any parameters or return values. Can only be called automatically by the GO program and cannot be referenced.

Difference:

  • Init can be applied to any package, and multiple can be defined repeatedly. The main function can only be used in the main package, and only one can be defined.

  • The order in which the two functions are executed:

    The go file in the main package is always executed by default. Init () calls to the same Go file are ordered from top to bottom.

    For different files in the same package, sort the file names “from smallest to largest” by string, and then call the init() function in each file in that order.

    For packages that do not depend on each other, the init() function in the main package is called in the order of the imports in the main package.

    If the package has dependencies, the last dependent is initialized first, for example, if the import order is main — > A — > B — > C, then the initialization order is C — > B — > A — > main, and the corresponding init method is executed once. The main package is always initialized last because it always depends on other packages