首页 > 应用开发 > Go语言 > Go基础:路径、文件名和包名的关系
工具与资源中心
帮助开发者更加高效的工作,提供围绕开发者全生命周期的工具与资源
https://developer.aliyun.com/tool/?spm=a1z389.11499242.0.0.65452413KFoX5Y&utm_content=g_1000295017
在 Golang 的文档中,Language Specification 页面,Package clause 下,指明了
A set of files sharing the same PackageName form the implementation of a package. An implementation may require that all source files for a package inhabit the same directory.也就是说,一个包所有的文件,必须位于同一个目录下
包名自然可以和文件夹名不一样,毕竟一个是导入路径,一个是包名
但不建议这么做,这样容易造成调用这个包的人,无法快速知道这个包的名称是什么
至于为什么不用目录名作为包名,我想也正如大家所说,为了避免目录中出现奇怪的字符,也为了调用者方便使用
在 Golang 的文档中, Language Specification 页面,Import declarations 下,有这样的说明
在 中有对
PackageName和ImportPath的具体描述:
ImportDecl = "import" ( ImportSpec | "(" { ImportSpec ";" } ")" ) .
ImportSpec = [ "." | PackageName ] ImportPath .
ImportPath = string_lit .![]()
The PackageName is used in qualified identifiers to access exported identifiers of the package within the importing source file. It is declared in the file block. If the PackageName is omitted, it defaults to the identifier specified in the package clause of the imported package. If an explicit period (.) appears instead of a name, all the package’s exported identifiers declared in that package’s package block will be declared in the importing source file’s file block and must be accessed without a qualifier.
也就是说,在执行导入的时候,若不手动定义包名,则从导入路径的源码文件中的 package 行获取包名,也即目录名和包名没有直接的关系。
1、import 导入的参数是路径,而非包名。
2、尽管习惯将包名和目录名保证一致,但这不是强制规定;
3、在代码中引用包成员时,使用包名而非目录名;
4、同一目录下,所有源文件必须使用相同的包名称(因为导入时使用绝对路径,所以在搜索路径下,包必须有唯一路径,但无须是唯一名字);
5、至于文件名,更没啥限制(扩展名为.go)
本文转自:https://developer.aliyun.com/article/791779?spm=a2c6h.12873581.0.0.6b4c767d002AhB&groupCode=othertech
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70003733/viewspace-2792985/ ,如需转载,请注明出处,否则将追究法律责任。