英文:
My main file can't find another file I created that I imported into the main file
问题
我有以下的文件结构:
- project/
- src/
- main/
- main.go
- viewmodels/
- home.go
- public/
我的项目位于:
~/go/src/
当我尝试运行我的主文件时,它抛出以下错误:
src/main/main.go:10:2: 无法在以下任何位置找到包“viewmodels”:
/usr/local/Cellar/go/1.5.3/libexec/src/viewmodels(来自$GOROOT)
/Users/nicholasrucci/go/src/viewmodels(来自$GOPATH)
看起来主文件正在错误的位置寻找package viewmodels
。根据我的理解,在阅读了如何编写Go代码和之前的程序正常运行后,我的配置是正确设置的,但显然出了些问题。
来自**.zshrc**的Go相关配置:
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/opt/go/libexec/bin
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:/usr/local/go/bin
main.go的片段:
package main
import (
"bufio"
"log"
"net/http"
"os"
"strings"
"text/template"
"viewmodels"
)
home.go的片段:
package viewmodels
import ()
对于发生了什么以及如何解决这个问题,有任何指导都将非常好。谢谢。
英文:
I have the following file structure:
- project/
- src/
- main/
- main.go
- viewmodels/
- home.go
- public/
My project is found in:
~/go/src/
When I attempt to run my main file it throws the error:
src/main/main.go:10:2: cannot find package "viewmodels" in any of:
/usr/local/Cellar/go/1.5.3/libexec/src/viewmodels (from $GOROOT)
/Users/nicholasrucci/go/src/viewmodels (from $GOPATH)
It looks like main is looking for package viewmodels
in the wrong location. From my understanding, after reading How to Write Go Code and the previous programs would run fine, my configuration is set up correctly, but obviously something is wrong.
Go related configurations from .zshrc:
export GOPATH=$HOME/go
export PATH=$PATH:/usr/local/opt/go/libexec/bin
export PATH=$PATH:$GOPATH/bin
export PATH=$PATH:/usr/local/go/bin
Snippet of main.go:
package main
import (
"bufio"
"log"
"net/http"
"os"
"strings"
"text/template"
"viewmodels"
)
Snippet of home.go:
package viewmodels
import ()
Any direction for what is going on and how I can fix this issue would be great. Thanks.
答案1
得分: 1
在这种情况下,你应该使用完整的包名作为导入路径:"project/src/viewmodels"
,假设项目位于/Users/nicholasrucci/go/src
下,但我建议你以不同的方式组织项目文件夹(例如,不使用src文件夹)。
另外,你也可以将你的GOPATH设置为项目文件夹的完整路径,这样你的main.go文件就可以像你所写的那样导入"viewmodels"
。
英文:
You should use the full package name for the import path: "project/src/viewmodels"
in this case, assuming project is under /Users/nicholasrucci/go/src
, but I would structure your project folder differently (no src folder for example)
Alternatively you could set your GOPATH to the fully qualified path to your project folder, which would then allow your main.go to import "viewmodels"
as you have it.
答案2
得分: 0
这对我来说完全没问题:
src/main/main.go
package main
import (
"viewmodels"
)
func main() {
viewmodels.Something()
}
src/viewmodels/home.go
package viewmodels
import ()
func Something() {
}
我猜测这可能是你的环境变量的问题。
英文:
This works just fine for me:
src/main/main.go
package main
import (
"viewmodels"
)
func main() {
viewmodels.Something()
}
src/viewmodels/home.go
package viewmodels
import ()
func Something() {
}
I'm guessing it is your env variables.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论