关于go:command-line-arguments:处理”未定义”错误消息


command-line-arguments : handling “undefined” error message

以下是源文件的组织方式

1
2
3
4
5
6
7
?-1 ~/Go/src/github.com/krmahadevan/packages
18:24 $ tree .
.
├── sample_main.go
└── sample_one.go

0 directories, 2 files

这是源代码的样子:

sample_one.go

1
2
3
4
5
6
7
package main

var data map[string]string

func init() {
    data = make(map[string]string, 0)
}

sample_main.go

1
2
3
4
5
6
7
8
package main

import"fmt"

func main() {
    data["foo"] ="bar"
    fmt.Println(data)
}

现在,当我尝试运行sample_main.go时,出现错误,指出未定义data

1
2
3
4
5
18:24 $ go run sample_main.go
# command-line-arguments
./sample_main.go:6:2: undefined: data
./sample_main.go:7:14: undefined: data
?-2 ~/Go/src/github.com/krmahadevan/packages

但是当我将代码构建为二进制文件然后执行它时,它运行良好。

1
2
3
4
5
6
? ~/Go/src/github.com/krmahadevan/packages
18:27 $ go build
? ~/Go/src/github.com/krmahadevan/packages
18:28 $ ./packages
map[foo:bar]
? ~/Go/src/github.com/krmahadevan/packages

我想了解为什么会这样?

环境:

1
2
18:31 $ go version
go version go1.11.4 darwin/amd64

我发现的最接近的帖子是:Golang:命令行参数未定义:变量

但是这篇文章讨论了在main中定义的范围变量。

但是我的问题陈述涉及在另一个go文件中定义并在main方法中访问的变量。


要了解原因,请阅读go命令文档:

Command go

Compile and run Go program

Usage:

1
go run [build flags] [-exec xprog] package [arguments...]

Run compiles and runs the named main Go package. Typically the package
is specified as a list of .go source files, but it may also be an
import path, file system path, or pattern matching a single known
package, as in 'go run .' or 'go run my/cmd'.

Compile packages and dependencies

Usage:

1
go build [-o output] [-i] [build flags] [packages]

Build compiles the packages named by the import paths, along with
their dependencies, but it does not install the results.

If the arguments to build are a list of .go files, build treats them
as a list of source files specifying a single package.

For more about specifying packages, see 'go help packages'. For more
about where packages and binaries are installed, run 'go help gopath'.

go run: Typically the package is specified as a list of .go source files.

对于您的go run示例,列出文件:

1
go run sample_main.go sample_one.go