无法理解如何在多个文件中编译go代码[重复]

无法理解如何在多个文件中编译go代码[重复]

问题描述:

This question already has an answer here:

OK, Go's major selling point is its ease of compilation and wonderful toolchain, but as a go newbie I'm really lost there and can't understand the documentation on that point.

I have a stack toy example within two files (one for the type definition and methods, called stack.go, one for the main program, called main.go), both are in my GOPATH/src/stacker directory.

  1. How should each file be named ? Does it have any importance at all ? Is there at least a convention ? A mandatory naming ?
  2. What should be the package name ? I understood they should use the same package name, but which one ? Is it stacker ?
  3. In main.go, how should I use the import directive to import stack.go ?

I have tried many combinations, none working until now.

</div>

此问题已经存在 在这里有答案 p>

  • 组织多文件Go项目 7个答案 span> li> ul> div>

    好,Go的主要卖点是易于编译和出色的工具链,但作为新手,我 p>

    我在两个文件中有一个堆栈玩具示例(一个用于类型定义和方法,称为 stack) .go code>(用于主程序的一个名为 main.go code>),都位于我的 GOPATH / src / stacker code>目录中。 p>

    1. 每个文件应如何命名? 它有什么重要性吗? 至少有约定吗? 强制命名? li>
    2. 软件包名称应该是什么? 我了解他们应该使用相同的软件包名称,但是哪个? 是 stacker code>吗? li>
    3. main.go code>中,我应该如何使用 import code>指令导入 stack.go code>吗? li> ol>

      我尝试了很多组合,但到目前为止都没有。 p> div>

  1. You can name the files however you like, just beware of special suffixes like _test and _<arch> (_darwin, _unix, etc.). Also note that files prefixed with . or _ won't be compiled into the package!
  2. It is recommended that you name the package like the folder the file is in, although it's possible (but confusing) to name a package differently in the declaration package mypkg
  3. If stack.go is in the same folder/package as main.go, you don't need to import. Everything delcared in stack.go is already available in main.go, because it is in the same package.

If stacker should compile into an executable, you should use package main.