英文:
Golang. Import only one file from package
问题
大家好。我是GO的新手,需要一些帮助。我有一个具有以下结构的项目:
但假设我在logic包中有100500个项目。如果我只需要导入特定包中的一个或两个文件,我该怎么办?我只能导入整个包吗?
英文:
Hi all. I am new in GO and need some help. I've got a project with this structure
But let's pretend that I have 100500 items in my logic package. What if I need import only one or two files for the specific package. Can I do it or I only can import a full package?
答案1
得分: 16
不,在Go语言中,你导入的是包而不是文件。然而,编译器通常只会在编译的二进制文件中包含实际引用的函数和类型,所以即使你导入了一个非常庞大的包(这本身就是不鼓励的),除非需要,它们通常不会被包含在最终的二进制文件中。
正如RayfenWindspear指出的那样,如果一个包足够大,你只想导入其中的一个或两个文件,那可能是一个很好的重构的信号。
英文:
No, in Go you import packages, not files. However, the compiler generally only includes in the compiled binary functions and types actually referenced, so even if you include a massive package in your import (which is discouraged anyway), they'll not usually be included in the final binary unless needed.
And as RayfenWindspear pointed out, if a package is large enough that you want to only import a file or two, that's probably a pretty good smell test that you need to refactor that package.
答案2
得分: 1
我意识到这个问题在很大程度上已经得到了回答。但是我还是想分享一下我的想法。
如果这些特定的文件可以独立于整个包工作,或者在进行一些小的修改后可以这样做,你可以简单地将这些文件复制到你想要使用它们的项目中。然后直接引用这些函数/方法等。但是,如果你在不同的项目中使用大型包的部分内容,将其拆分为较小的包肯定更合适。然后,你可以在任意多个项目中独立地使用这些部分,而不会带来额外的负担。
英文:
I realize this question is largely already answered. But here are my thoughts anyways.
If the specific files can work independently from the rest of the package or do so with some minor modifications you can just simply copy those files to the project you want to use them in. Then reference the functions/methods/etc directly. But if you are using parts of a big package in various projects it would definitely be more suitable to break it into smaller packages. Then you can use those parts independently in as many projects as you wish without the excess baggage.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论