In Go, packages encapsulate related code and data. To reuse functionality from one package in another, you must import the first package into the latter.
Consider the following project structure:
src |-->config |--> config.go |-->otherPackage |--> otherFile.go |-->main.go
The file config.go contains a type definition for Config:
package config type Config struct { // ... }
You want to use the Config type in the file otherFile.go:
package otherPackage func SomeFunction(target float64, entries [2]float64, config config.Config) { // ... }
When attempting to import the config package, you encounter the following errors:
The first error indicates that you have imported the config package but are not using it anywhere in your code. The second error indicates that the Config type is not recognized in the current scope.
To resolve this issue, you need to import the package using its full path instead of a relative path. Additionally, you need to qualify the Config type with its package name when referencing it in your code.
package otherPackage import ( "fmt" "math" "your-project/src/config" ) func SomeFunction(target float64, entries [2]float64, config config.Config) { // ... }
By importing the package with its full path, you explicitly state where to find the Config type. Qualifying the type with its package name ensures that the compiler knows which Config type you are referring to.
Note: If the package name you are importing is the same as a variable or type in your current scope, you will need to rename the variable or type to avoid conflicts.
The above is the detailed content of How to Use a Type Defined in One Package in Another Package in Go?. For more information, please follow other related articles on the PHP Chinese website!
if($res){
return json_encode(array('code'=>1,'msg'=>'成功'));
}else{
return json_encode(array('code'=>0,'msg'=>'失败'));
}
}
public function
}