Solution to the problem that golang cannot import packages:
Import packages:
Standard package use is a given short path, such as "fmt", "net/http"
For your own package, you need to specify a directory under the working directory (GOPATH). The import package is actually based on the working directory. Folder directory
Multiple ways to import packages:
Import directly from the
$GOPATH/src
directoryimport "test/lib"
(The path is actually$GOPATH/src/test/lib)
Alias import:
import alias_name "test/lib"
, when used in this way, you can directly use the aliasUse the dot to import:
import. "test/lib"
, function When using it, simply omit the package name
and use underscores to import: import _ "test/lib". This operation actually just introduces the package. When a package is imported, all its init() functions will be executed, but sometimes you don't really need to use these packages, you just want its init() function to be executed. At this time, you can use the _ operation to reference the package. Even if you use the _ operation to reference a package, you cannot call the exported functions in the package through the package name, but just to simply call its init function ().
Often these init functions register the engines in their own packages so that they can be easily used by the outside world. For example, packages that implement database/sql all call sql.Register(name) in the init functions. string, driver driver.Driver)
Register yourself, and then it can be used externally.
Relative path importimport "./model"//
The model directory in the same directory as the current file, but this method of import is not recommended
Package import Process description:
The initialization and execution of the program start from the main package. If the main package also imports other packages, they will be imported in sequence during compilation. Sometimes a package will be imported by multiple packages at the same time, so it will only be imported once (for example, many packages may use the fmt package, but it will only be imported once, because there is no need to import it multiple times).
When a package is imported, if the package also imports other packages, the other packages will be imported first, and then the package-level constants and variables in these packages will be initialized, and then init will be executed. function (if any), and so on. After all imported packages are loaded, the package-level constants and variables in the main package will be initialized, then the init function in the main package will be executed (if it exists), and finally the main function will be executed. The following figure explains the entire execution process in detail:
Note:
There are several ways to import Go packages, with different uses. The code is stored uniformly in the working directory. There will be many packages in the working directory. Different packages are organized by directory, and the packages are composed of multiple code files. When importing a package, import it according to the unique path of the package. The imported package must be used by default. If it is not used, the compilation will fail and needs to be removed to reduce the introduction of unnecessary code. Of course, there are other usage scenarios. By default, we use the file name as the package name for easy understanding. Different packages organize different function implementations to facilitate understanding.
Did you use the package source code or .a when compiling?
A non-main package will generate a .a
file after compilation (generated in a temporary directory, unless it is installed to $GOROOT
or # using go install ##$GOPATH, otherwise you won’t be able to see it. a), used for subsequent executable program linking. For example, the source code path corresponding to the package in the Go standard library is:
$GOROOT/src, and the path to the compiled .a file of the package in the standard library is
$GOROOT/pkg/darwin_amd64 Down. A strange question arises in my head. When compiling, does the compiler use .a or source code?
- When using third-party packages, when the source code and .a are both installed, the compiler links to the source code. The so-called use of third-party package source code is actually a link to the
.a
file in the temporary directory compiled with the latest source code.
- Are the packages in the Go standard library also like this? For standard libraries, such as fmt, when compiling, should you use the source code under $GOROOT/src or the compiled .a under $GOROOT/pkg? However, unlike custom packages, even if you modify the source code of the fmt package (without recompiling the GO installation package), when the user source code is compiled, there will be no attempt to recompile the fmt package. The link will still be compiled when the link is made. fmt.a
In Go language, is the last element in the path after import the package name or the path name?
- #The last element after import should be the path, which is the directory, not the package name. But many times, the path name is the same as the package name
import m "lib/math" m refers to the only package in the lib/math path. If the compiler finds two packages in this path, it is not allowed. Compile Error reporting
Recommended tutorial: "go language tutorial"
The above is the detailed content of What should I do if golang cannot import packages?. For more information, please follow other related articles on the PHP Chinese website!

Go's strings package provides a variety of string manipulation functions. 1) Use strings.Contains to check substrings. 2) Use strings.Split to split the string into substring slices. 3) Merge strings through strings.Join. 4) Use strings.TrimSpace or strings.Trim to remove blanks or specified characters at the beginning and end of a string. 5) Replace all specified substrings with strings.ReplaceAll. 6) Use strings.HasPrefix or strings.HasSuffix to check the prefix or suffix of the string.

Using the Go language strings package can improve code quality. 1) Use strings.Join() to elegantly connect string arrays to avoid performance overhead. 2) Combine strings.Split() and strings.Contains() to process text and pay attention to case sensitivity issues. 3) Avoid abuse of strings.Replace() and consider using regular expressions for a large number of substitutions. 4) Use strings.Builder to improve the performance of frequently splicing strings.

Go's bytes package provides a variety of practical functions to handle byte slicing. 1.bytes.Contains is used to check whether the byte slice contains a specific sequence. 2.bytes.Split is used to split byte slices into smallerpieces. 3.bytes.Join is used to concatenate multiple byte slices into one. 4.bytes.TrimSpace is used to remove the front and back blanks of byte slices. 5.bytes.Equal is used to compare whether two byte slices are equal. 6.bytes.Index is used to find the starting index of sub-slices in largerslices.

Theencoding/binarypackageinGoisessentialbecauseitprovidesastandardizedwaytoreadandwritebinarydata,ensuringcross-platformcompatibilityandhandlingdifferentendianness.ItoffersfunctionslikeRead,Write,ReadUvarint,andWriteUvarintforprecisecontroloverbinary

ThebytespackageinGoiscrucialforhandlingbyteslicesandbuffers,offeringtoolsforefficientmemorymanagementanddatamanipulation.1)Itprovidesfunctionalitieslikecreatingbuffers,comparingslices,andsearching/replacingwithinslices.2)Forlargedatasets,usingbytes.N

You should care about the "strings" package in Go because it provides tools for handling text data, splicing from basic strings to advanced regular expression matching. 1) The "strings" package provides efficient string operations, such as Join functions used to splice strings to avoid performance problems. 2) It contains advanced functions, such as the ContainsAny function, to check whether a string contains a specific character set. 3) The Replace function is used to replace substrings in a string, and attention should be paid to the replacement order and case sensitivity. 4) The Split function can split strings according to the separator and is often used for regular expression processing. 5) Performance needs to be considered when using, such as

The"encoding/binary"packageinGoisessentialforhandlingbinarydata,offeringtoolsforreadingandwritingbinarydataefficiently.1)Itsupportsbothlittle-endianandbig-endianbyteorders,crucialforcross-systemcompatibility.2)Thepackageallowsworkingwithcus

Mastering the bytes package in Go can help improve the efficiency and elegance of your code. 1) The bytes package is crucial for parsing binary data, processing network protocols, and memory management. 2) Use bytes.Buffer to gradually build byte slices. 3) The bytes package provides the functions of searching, replacing and segmenting byte slices. 4) The bytes.Reader type is suitable for reading data from byte slices, especially in I/O operations. 5) The bytes package works in collaboration with Go's garbage collector, improving the efficiency of big data processing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
