In Go language, the purpose of packages is the same as that of libraries or modules in other languages, and supports modularity, encapsulation, separate compilation and reuse. ——"The Go Programming Language"
Sometimes I need to write a package myself to facilitate multiple use, but I encountered problems when importing the package I wrote. I thoughtimport
Part of it is directly the path to the package, but after actually writing it myself, I found that this is not the case. This part is actually interpreted as an identifier, which is composed of aThe file determines that the general meaning is indeed the end of the path.
The concept of modules in Go actually also includes some version management functions. Therefore, Go's module and version management is not an easy task for learning or development, and the Go team is also working hard to adjust and optimize. This article can only represent the current versiongo1.20.2
If the version is updated in the future, I will make notes.
What is it
Each Go module isDetermine that the file describes the properties of the module, such as whether the path stored by the module depends on other modules, the minimum use of Go version, etc. for example
[email protected]
ofContents are:
module /x/mod go 1.17 require /x/tools v0.1.12 // tagx:ignore
Then when compiling, the compiler will look for this module., if any, find the corresponding one
, and then import the functions used in the corresponding package for compilation.
Here are two questions:
- Where to find the modules of Go?
- How to get Go to search for packages from a specific directory?
The difference between a module and a package is that a module is a collection of a series of packages, and there is a
Files can even be compiled directly into a program by themselves. And the package is one or more
.go
Files are used to divide package level scopes (package level) and can be used as libraries in other languages. The scope should be: module >>> package >>> source code file. However, in some cases, the three words package, module, and library can be mixed (they are different in different cases, but they refer to the same thing).
Need to pay attentionpackage main
It's an exception, it's not a library (although there is apackage
), but is used to indicate that this is a program that can be executed separately.
Create modules and write package contents
Here is an example for demonstration. The example of the demonstration comes from Section 2.7 in "The Go Programming Language", which is used to count how many bits of a binary number are1
, for example, input1
return1
,enter0x1234567890ABCDEF
return32
。
Create a new folderpopcount
, and then create a namedFile:
$ mkdir popcount $ cd popcount $ touch
Enter the following (the following algorithm is not the fastest, nor is it the easiest to understand, but it can explain a lot):
package popcount // Is it used to count the i-th position?var pc [256]byte //Initialize the packagefunc init() { for i := range pc { pc[i] = pc[i/2] + byte(i&1) } } // PopCount returns how many bits are 1 in x.func PopCount(x uint64) int { return int(pc[byte(x>>(0*8))] + pc[byte(x>>(1*8))] + pc[byte(x>>(2*8))] + pc[byte(x>>(3*8))] + pc[byte(x>>(4*8))] + pc[byte(x>>(5*8))] + pc[byte(x>>(6*8))] + pc[byte(x>>(7*8))]) }
In the above:pc
The first letter is lowercase, so it can only bepopcount
Used in the package, andPopCount
The initial letter is capitalized, so it can be importedpopcount
Used in the package file.
Continue inpopcount
Passedgo mod init
Command creationThe file is as follows:
$ go mod init test/popcount go: creating new : module test/popcount go: to add module requirements and sums: go mod tidy $ ls
You can see moredocument.
Import self-built packages (local packages)
Then create a new directory elsewherepop_test
To write the program code that uses this package (can be used withpopcount
In the same directory, or elsewhere), select andpopcount
In the same directory, as follows:
$ cd .. $ mkdir pop_test
Then inpop_test
Create a new one in the:
$ go mod init pop_test
At this timeThe content should be in the following style:
module pop_test go 1.20
Open it with your favorite text editor, add these two sentences at the end, and turn it into the following style:
module pop_test go 1.20 require test/popcount v0.0.0 replace test/popcount => ../popcount
The last two sentences cannot be omitted, and no less sentence can be done.
The first sentence is to illustrate the usepopcount
The second sentence is because we are using local package instead of downloading imported libraries, and the local package location is notGOROOT/src/test/popcount
In the Go compiled, it cannot be found (aboutGOROOT
There are some contents later). The second sentence is actually similar to the options in the C compiler-I
. (The two problems at the beginning are solved here)
Then create a new oneFile, enter the following:
package main import ( "fmt" "test/popcount" ) func main() { a := (0x1234567890ABCDEF) (a) }
At this time, you should see the following results:
$ go run
32
This method is officially recommended, but the problem is to be in the root directory of the project (as abovepop_test
Create a ) under )。
The second method
The following method is set according to the operating mechanism. To be honest, it is not very convenient to manage, but it is quite convenient in some cases.
As mentioned above: Go is inGOROOT/src
Looking for a package, a package isGOROOT/src/package name
. Then you can directlyGOROOT/src
Place the built local package according to the structure of the package name, and then you can use it directly in the program code without creating a one in the project root directory.The file indicates the location of the local package used.
Find yourGOROOT
,as follows:
$ go env GOROOT /usr/local/go
Yours may not be/usr/local/go
. These environment variables in Go are best usedgo env
Check it out if you useecho $GOROOT
You may find that this environment variable is empty.
Also, it is best not to useexpert
Modify this environment variable in the shell configuration file, because the standard library is in the defaultGOROOT
Once you switch, then you'd better copy all these standard libraries to the new location. Use directly in special circumstancesexpert
Modify, but only switch in the current terminal, do not replace it completely.
The biggest disadvantage of this method is that it is modified/usr/local/go
, these default directories are automatically configured through scripts for most periods. If you modify them, there may be problems and conflicts in the future, and you forget to modify this part, that is a big problem.
So if you have to use this method, it is best to create a folder that will not be duplicated (or will not be very likely), for exampleZhongUncle
, and then create packages and configurations in it。
This is the article about creating a package and using Go (importing local packages and precautions). For more related Go to create packages and import content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!