英文:
Importing a file that resides in the same directory
问题
让我来为你翻译一下:
让我在Go语言中编程时感到困难的一件事是,我必须将我想要导入的模块(或者我应该称它们为包?)放在我的主模块中的单独目录中,而且更重要的是,必须有一个src
目录。有没有一种方法可以导入与主模块位于同一目录中的文件呢?
当前的目录结构如下:
main.go
src/lib/lib.go
现在我可以使用import "lib"
来导入。
我希望有以下目录结构:
main.go
lib.go
并且仍然能够让编译器找到lib.go
文件。
英文:
One thing that makes it difficult for me to program in Go is that I must put modules (or I should call them packages?) that I want to import in my main module in separate directories, and even more, there must be an src
directory. Is there a way to import the file that resides in the same dir as the main module?
Current directory layout:
main.go
src/lib/lib.go
Now I can do import "lib"
What I would love to have:
main.go
lib.go
And still make the compiler happily find lib.go
.
答案1
得分: 3
这是你想要的布局:
main.go
lib.go
这没有问题。Go允许你有这样的文件结构,并且很多Go程序都在使用。但是它们都需要被定义为package main
。你可能会问为什么?因为这是语言规范。Go的发明者就是这样定义的。
好处是,你不需要导入任何东西,因为Go编译器知道这两个文件属于package main
。
英文:
This is the layout you want to have:
main.go
lib.go
And that is no problem. Go allows you to have such a file structure. And it is used by a lot of Go programms. But they both need to be defined as package main
. If you ask why? Because that is the language specification. The inventors of Go defined it like that.
The good thing here is, that you don't have to import anything, because the go compiler knows that these two files belong into the package main.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论