duandun2218 2019-01-27 13:03
浏览 84


Following is how the source files are organized

✘-1 ~/Go/src/github.com/krmahadevan/packages 
18:24 $ tree .
├── sample_main.go
└── sample_one.go

0 directories, 2 files

Here's how the source code looks like:


package main

var data map[string]string

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


package main

import "fmt"

func main() {
    data["foo"] = "bar"

Now when I attempt at running sample_main.go I get errors stating that data is undefined.

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

But when I build the code into a binary and then execute it, it runs fine.

✔ ~/Go/src/github.com/krmahadevan/packages 
18:27 $ go build
✔ ~/Go/src/github.com/krmahadevan/packages 
18:28 $ ./packages 
✔ ~/Go/src/github.com/krmahadevan/packages

I would like to understand why is this behavior ?


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

The closest I found was this post : Golang : command-line-arguments undefined: variable

But this post talks about scoped variables that are defined in main.

But my problem statement involves variables defined in another go file and accessed in the main method.

  • 写回答

1条回答 默认 最新

  • dttphb59319 2019-01-27 13:10

    To understand why, read the go command documentation:

    Command go

    Compile and run Go program


    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


    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.

    For your go run example, list the files:

    go run sample_main.go sample_one.go
    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 加一个K2暂停音乐的功能
  • ¥15 完成虚拟机环境配置,还有安装kettle
  • ¥15 2024年全国大学生数据分析大赛A题:直播带货与电商产品的大数据分析 问题5. 请设计一份优惠券的投放策略,需要考虑优惠券的数量、优惠券的金额、投放时间段和投放商品种类等因素。求具体的python代码
  • ¥15 有人会搭建生鲜配送自营+平台的管理系统吗
  • ¥15 用matlab写代码
  • ¥30 motoradmin系统的多对多配置
  • ¥15 求组态王串口自定义通信配置方法或代码?
  • ¥15 实验 :UML2.0 结构建模
  • ¥20 用vivado写数字逻辑实验报告撰写,FPGA实验
  • ¥15 为什么shp文件会有这种小方块?