go同一级目录下定义的struct,函数等的相互引用,是如何实现的?

是不是同一级目录下,定义的struct,函数、方法 interface的名称必须是唯一的?

这样也可以在同一级目录下的其它文件里面直接引用了?

好像同一级目录下也不需要import类似这种的操作也可以直接用了。

这个Go源代码中是如何体现的?

阅读 3.3k
1 个回答

你说的同一级目录下定义的结构函数可以直接引用,准确的说,这个是“包”的概念。

在 Go 语言规范的 Packages 节里这么描述:

Go programs are constructed by linking together packages. A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package. Those elements may be exported and used in another package.

对你的问题,重点在于 A package in turn is constructed from one or more source files that together declare constants, types, variables and functions belonging to the package and which are accessible in all files of the same package.

包是属于这个包的多个包含常量、类型、变量和函数声明的源文件组成的,而且同一个包里文件可以访问这个包里的常量、类型、变量、函数。

还记得你的go源码最开头写的那行 package main 么?这就定义了源文件属于main包,main包里声明的东西,main包的源文件都可以访问。

理所当然的,既然同一个包下的声明能互相访问,自然会要求不能重复声明常量、类型、变量和函数。

另外你还问了:

这样也可以在同一级目录下的其它文件里面直接引用了?

准确地说,是因为实现要求属于包的源文件放在同一目录下,而同一个包的文件可以访问包里声明的东西,所以才表现出“同一级目录下其他文件里直接引用”。

语言规范是这么说的:

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.
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题