英文:
Using package main for all files, still says undefined
问题
我目前有3个文件,它们的顶部都有package main
。
GOPATH/src/example.com/myweb/main.go
GOPATH/src/example.com/myweb/api.go
GOPATH/src/example.com/myweb/viewmodels/home.go
当我编译时,出现了以下错误:
./main.go:21: undefined: Home
./main.go:39: api.Home undefined (type API has no field or method Home)
我正在使用以下命令进行编译:
go build
如果我这样做:
go build main.go api.go viewmodels/home.go
它会显示"no such file or directory",然后是一个不存在的文件路径:
GOPATH/src/example.com/myweb/viewmodels.main.go
如果我使用的是package main
,这个命令不应该正常工作吗?
英文:
I have 3 files currently, they all have package main
at the top.
GOPATH/src/example.com/myweb/main.go
GOPATH/src/example.com/myweb/api.go
GOPATH/src/example.com/myweb/viewmodels/home.go
When I compile I get the error:
./main.go:21: undefined: Home
./main.go:39: api.Home undefined (type API has no field or method Home)
I am compiling using:
go build
If I do this:
go build main.go api.go viewmodels/home.go
It says no such file or directory and then a path to a file that doesnt' exist:
GOPATH/src/example.com/myweb/viewmodels.main.go
If I am using package main, should this just work with go build ?
答案1
得分: 1
你不能在同一个目录中混合使用两个不同的包。每个目录都是一个独立的包。
Go文档(参见:golang.org/doc/code.html)对于包的相关情况有以下说明:
- 每个包由一个或多个Go源文件组成,位于同一个目录中。
- 包的导入路径由其目录路径确定。
解决你的问题的方法如下:
- 对于
$GOPATH/src/example.com/myweb/viewmodels/home.go
,使用package viewmodels
。 - 对于
$GOPATH/src/example.com/myweb/main.go
和$GOPATH/src/example.com/myweb/api.go
,使用package main
。 - 在使用
viewmodels
包的文件(例如main.go、api.go)中添加import "example.com/myweb/viewmodels"
。
你的项目结构可能如下所示:
英文:
You cannot mix two different packages in one directory. Each directory is its own package.
The go documentation (see: golang.org/doc/code.html) states the following about packages that is relevant to your situation:
> - Each package consists of one or more Go source files in a single directory.
> - The path to a package's directory determines its import path.
The solution to your problem is:
- Use
package viewmodels
for$GOPATH/src/example.com/myweb/viewmodels/home.go
- Use
package main
for$GOPATH/src/example.com/myweb/main.go
and$GOPATH/src/example.com/myweb/api.go
- Add
import "example.com/myweb/viewmodels"
to the files using theviewmodels
package (e.g. main.go, api.go)
Your project would look something like this:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论