Import and Not Used Error Explained
When importing a package in Go, the compiler expects to find actual usage of that package within the source file. If an imported package is not utilized, you may encounter the "imported and not used" error.
In the provided example, the import of the "./api" package triggers this error. The reason for this is that you're not actually using anything from the api package. While you have files stored in the api folder, you need to explicitly include those files using the import statement:
import ( "log" "net/http" "os" "github.com/emicklei/go-restful" "github.com/emicklei/go-restful/swagger" // Include the api package _ "./api" )
By using the underscore (_) as a prefix for the import, you're essentially telling the compiler to skip importing the package code but still execute its initialization function (if any). This ensures that your api folder's package initialization code runs without triggering the error.
Alternatively, if you intend to use specific functions or types from the api package, you can import them explicitly:
import ( // Others here api "my-custom-path/api-package" )
In this case, you can utilize functions or types from the api package by using the "api" alias, e.g.:
api.SomeFunction()
Remember, it's generally recommended to import packages via the GOPATH to avoid relative imports.
The above is the detailed content of Why Do I Get an \'Imported and Not Used\' Error in Go?. For more information, please follow other related articles on the PHP Chinese website!