go - 如何从 Go 程序中的另一个文件导入定义?

标签 go scope package

<分区>

我有以下文件:

gopackage/main.go:

package main

func main () {
  foo();
}

gopackage/otherfile.go:

package main

import "fmt"

func foo() {
  fmt.Print("foo\n")
}

显然,main.go 中对 foo 的引用并未解析为 otherfile.go< 中 foo 的定义:

> go run main.go
# command-line-arguments
./main.go:4: undefined: foo

为什么不呢?有人告诉我,同一目录中的所有文件都包含一个包,这是一个范围。

最佳答案

Compile and run Go program

Usage:

go run [build flags] [-exec xprog] gofiles... [arguments...]

Run compiles and runs the main package comprising the named Go source files. A Go source file is defined to be a file ending in a literal ".go" suffix.

列出所有的gofiles,

go run main.go otherfile.go

或者,在 Linux 和其他类 Unix 系统上,*.go 是目录中所有 .go 文件的通配符,

go run *.go

关于go - 如何从 Go 程序中的另一个文件导入定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29010856/

相关文章:

go - 如果我不在任何地方阅读消息,则不会为 gorilla /websocket 调用 CloseHandler,我最终只会收到写入错误

Go:我是否创造了太多的值(value)?

HTTP NTLM 身份验证

scope - QML 组件作用域拼图

c++ - 派生模板类访问基类成员数据

Python:写入包内另一个目录的正确方法

go - 节点结构 slice 中未定义的属性

堆栈上的 C++ 变量似乎没有在函数作用域的末尾被释放

linux - 如何将共享库打包成deb包

ubuntu - golang 获取包报错