Notes on using Golang packages

1) When packaging a file, the package corresponds to a folder. For example, the package name corresponding to the utils folder here is utils. The package name of the file is usually the same as the folder name where the file is located, generally in lowercase letters .

2) When a file wants to use other package functions or variables, it needs to import the corresponding package first

  • Import method 1: import "package name"
  • Import method 2:
import(
  "包名"
  "包名"
)

3) The package directive is on the first line of the file, followed by the import directive.

4) When importing packages, the path starts from the src of SGOPATH, without src, the compiler will automatically import from src

5) In order to allow files in other packages to access the functions of this package, the first letter of the function name needs to be capitalized, similar to other

The public of the language, so that it can be accessed across packages. such as utils.go

If the variable can be accessed by other packages, it is also defined as uppercase.

6) When accessing other package functions, the syntax is package name.function name, such as in the main.go file here (the same is true for variables)

 7) If the package name is long, Go supports aliasing the package, pay attention to the details: after taking the alias, the original package name cannot be used (alias u, then use the new alias to access the variables and functions of this package)

import (
	u "day1/base/package_test/utils"
	"fmt"
)

func main() {
	n := u.Sum(1, 2)
	fmt.Println(n)
	fmt.Println(u.Number1)
}

8) Under the same package, there cannot be the same function name (nor the same global variable name), otherwise the report will be repeated.

9) If you want to compile it into an executable program file, you need to declare the package as main, which is a syntax specification. If you are writing a library, the package name can be customized. (In fact, there can only be one main package)

In the actual development process, binary files are actually generated, and executable files can be handed over to the other party for use.

Guess you like

Origin blog.csdn.net/qq_34556414/article/details/130414396