英文:
Can't understand how to compile go code in multiple files
问题
好的,Go的主要卖点是它的编译简便性和出色的工具链,但作为一个Go的新手,我真的迷失了,无法理解关于这一点的文档。
我有一个简单的堆栈示例,包含两个文件(一个用于类型定义和方法,名为stack.go
,一个用于主程序,名为main.go
),两个文件都在我的GOPATH/src/stacker
目录中。
- 每个文件应该如何命名?它们是否有任何重要性?是否有约定?是否有强制命名规则?
- 包名应该是什么?我理解它们应该使用相同的包名,但是是哪个包名?是
stacker
吗? - 在
main.go
中,我应该如何使用import
指令来导入stack.go
?
我尝试了许多组合,但目前都没有成功。
英文:
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.
- How should each file be named ? Does it have any importance at all ? Is there at least a convention ? A mandatory naming ?
- What should be the package name ? I understood they should use the same package name, but which one ? Is it
stacker
? - In
main.go
, how should I use theimport
directive to importstack.go
?
I have tried many combinations, none working until now.
答案1
得分: 9
- 你可以随意命名文件,但要注意特殊后缀,如
_test
和_<arch>
(_darwin
,_unix
等)。还要注意以.
或_
开头的文件不会被编译到包中! - 建议将包的名称与文件所在的文件夹相同,尽管在声明
package mypkg
中可以使用不同的包名(但会令人困惑)。 - 如果
stack.go
与main.go
在同一个文件夹/包中,你不需要导入。因为它们在同一个包中,所以stack.go
中声明的所有内容已经在main.go
中可用。
如果 stacker
应该编译为可执行文件,你应该使用 package main
。
英文:
- 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! - 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
- If
stack.go
is in the same folder/package asmain.go
, you don't need to import. Everything delcared instack.go
is already available inmain.go
, because it is in the same package.
If stacker
should compile into an executable, you should use package main
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论