英文:
Some tips with Go and Gogland
问题
- 我选择了“运行类型”为Package - 以运行整个项目而不仅仅是主文件。为什么它找不到主包?
- 如何导入util.myprinter包到main.go中以便使用它?
请帮助我。
英文:
Hi all. I'm very new with Go and Gogland. I have a project
- I choose "Run kind" as Package - to run not only main file but a project. Why it cannot find main package??
- How to import util.myprinter package to main.go to use it??
Please, help me
答案1
得分: 10
首先,你的Go 工作区的一般结构似乎是错误的。你需要让它看起来更像这样:
D:
|-- go_projects
| |-- bin
| |-- pkg
| |-- src
| | |-- FirstSteps
| | | |-- main.go
| | | +-- util
| | | +-- myprinter.go
| | |-- SecondProject
| | |-- ThirdProject
...
其次,你的import
语句似乎是空的,我不知道GoLand是如何工作的,但是如果你想使用myprinter.go
文件中的内容,你需要导入util
包,假设myprinter.go
文件在顶部声明了package
为util
。
// FirstSteps/main.go
package main
import (
"FirstSteps/util"
)
func main() {
util.MyPrinterFunc()
}
当然,要能够使用util
中的任何内容,首先必须有一些内容...
// FirstSteps/util/myprinter.go
package util
func MyPrinterFunc() {
// do stuff...
}
编辑:对不起,我实际上没有最初回答你的问题。你得到错误消息Cannot find package 'main'
是因为我之前提到的错误的工作区设置。Package path
告诉GoLand要运行的包相对于$GOPATH/src
目录的位置。因此,在正确设置工作区之后,你应该将Package path
设置为FirstSteps
,因为该包的绝对路径将是$GOPATH/src/FirstSteps
。如果以后你想运行util
包,你可以将Package path
指定为FirstSteps/util
,以便GoLand能够找到它。
英文:
First, the general structure of your Go workspace seems to be wrong. You need to make it look more like this:
D:
|-- go_projects
| |-- bin
| |-- pkg
| |-- src
| | |-- FirstSteps
| | | |-- main.go
| | | +-- util
| | | +-- myprinter.go
| | |-- SecondProject
| | |-- ThirdProject
...
Second your import
statement seems to be empty, I have no idea how GoLand works but if you want to use whatever is in your myprinter.go
file, you will need to import the util
package, assuming that the myprinter.go
file declares its package
as util
at the top.
// FirstSteps/main.go
package main
import (
"FirstSteps/util"
)
func main() {
util.MyPrinterFunc()
}
And of course to be able to use anything from util
there first must be something...
// FirstSteps/util/myprinter.go
package util
func MyPrinterFunc() {
// do stuff...
}
Edit: I'm sorry, I didn't actually answer your question initially. You're getting the error Cannot find package 'main'
because of the wrong workspace setup I already mentioned. The Package path
tells GoLand where the package you want to run is relative to the $GOPATH/src
directory. So after you've setup your wrokspace correctly, you should set the Package path
to FirstSteps
since that package's absolute path will be $GOPATH/src/FirstSteps
. If, later, you want to run the util
package you would specify Package path
as FirstSteps/util
for GoLand to be able to find it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论