Home >Backend Development >Golang >Why Can't I Import a Specific Type in Go?
Problem:
A user encounters issues when importing a type from a separate package in their Go project structure. The import statements lead to warnings about unused imports or undefined types, even though the type is used in function declarations.
Project Structure:
src |-- config |-- config.go |-- otherPackage |-- otherFile.go |-- main.go
Import Attempt:
import ( "fmt" "math" "../config" )
Errors:
Cause:
The problem arises because of incorrect import syntax. In Go, it is not possible to import specific types or functions from a package. Only the entire package can be imported.
Solution:
To resolve the issue, the import statement needs to be modified as follows:
import ( "fmt" "math" "full/import/path/of/config" )
Package and Type Reference:
Since the entire package is imported, the type must be referenced using its fully qualified name:
func function(... config.Config) {}
Variable Shadowing:
If a variable with the same name as the imported package is declared in the current scope, it will shadow the package. To avoid this, rename the variable to something else, such as:
func function(... config.Config) {} var cfg config.Config
The above is the detailed content of Why Can't I Import a Specific Type in Go?. For more information, please follow other related articles on the PHP Chinese website!