目录结构
Go语言代码根据目录组织,一个包由多个文件组织,文件必须属于同一个目录下。标准库go/parser包中的parser.ParseDir用于解析目录内的全部Go语言文件,返回的map[string]ast.Package包含多个包信息。而parser.ParseFile用于解析单个文件,返回的ast.File包含文件内部代码信息。而每个ast.Package正是由多个ast.File文件组成。它们直接的逻辑关系如下图所示:
文件结构
type File struct {Doc *CommentGroup // associated documentation; or nilPackage token.Pos // position of "package" keywordName *Ident // package nameDecls []Decl // top-level declarations; or nilScope *Scope // package scope (this file only)Imports []*ImportSpec // imports in this fileUnresolved []*Ident // unresolved identifiers in this fileComments []*CommentGroup // list of all comments in the source file}
parser.ParseDir解析目录结构返回包含多个包的map,返回包的总体逻辑关系如下图所示:
多个包可以构成完整的可执行程序。每个包内部通过文件组织代码的导入和声明语句。而单个文件可以由parser.ParseFile完成解析,文件内部的逻辑关系如下图:
