无法理解如何在多个文件中编译Go代码。

huangapple go评论145阅读模式
英文:

Can't understand how to compile go code in multiple files

问题

好的,Go的主要卖点是它的编译简便性和出色的工具链,但作为一个Go的新手,我真的迷失了,无法理解关于这一点的文档。

我有一个简单的堆栈示例,包含两个文件(一个用于类型定义和方法,名为stack.go,一个用于主程序,名为main.go),两个文件都在我的GOPATH/src/stacker目录中。

  1. 每个文件应该如何命名?它们是否有任何重要性?是否有约定?是否有强制命名规则?
  2. 包名应该是什么?我理解它们应该使用相同的包名,但是是哪个包名?是stacker吗?
  3. 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.

  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.

答案1

得分: 9

  1. 你可以随意命名文件,但要注意特殊后缀,如 _test_<arch> (_darwin, _unix 等)。还要注意以 ._ 开头的文件不会被编译到包中!
  2. 建议将包的名称与文件所在的文件夹相同,尽管在声明 package mypkg 中可以使用不同的包名(但会令人困惑)。
  3. 如果 stack.gomain.go 在同一个文件夹/包中,你不需要导入。因为它们在同一个包中,所以 stack.go 中声明的所有内容已经在 main.go 中可用。

如果 stacker 应该编译为可执行文件,你应该使用 package main

英文:
  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.

huangapple
  • 本文由 发表于 2013年3月8日 22:07:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/15295819.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定