使用package main来处理所有文件,但仍然显示未定义。

huangapple go评论73阅读模式
英文:

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源文件组成,位于同一个目录中。
  • 包的导入路径由其目录路径确定。

解决你的问题的方法如下:

  1. 对于$GOPATH/src/example.com/myweb/viewmodels/home.go,使用package viewmodels
  2. 对于$GOPATH/src/example.com/myweb/main.go$GOPATH/src/example.com/myweb/api.go,使用package main
  3. 在使用viewmodels包的文件(例如main.go、api.go)中添加import "example.com/myweb/viewmodels"

你的项目结构可能如下所示:

使用package main来处理所有文件,但仍然显示未定义。

英文:

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:

  1. Use package viewmodels for $GOPATH/src/example.com/myweb/viewmodels/home.go
  2. Use package main for $GOPATH/src/example.com/myweb/main.go and $GOPATH/src/example.com/myweb/api.go
  3. Add import "example.com/myweb/viewmodels" to the files using the viewmodels package (e.g. main.go, api.go)

Your project would look something like this:

使用package main来处理所有文件,但仍然显示未定义。

huangapple
  • 本文由 发表于 2016年4月18日 03:20:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/36681089.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定