英文:
How do I import definitions from another file in a Go program?
问题
我有以下文件:
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
为什么会这样?我被告知同一目录下的所有文件组成一个单一的包,也就是一个单一的作用域。
英文:
I have the following files:
gopackage/main.go
:
package main
func main () {
foo();
}
gopackage/otherfile.go
:
package main
import "fmt"
func foo() {
fmt.Print("foo\n")
}
Apparently, the reference to foo
from main.go
does not resolve to the definition of foo
in otherfile.go
:
> go run main.go
# command-line-arguments
./main.go:4: undefined: foo
Why not? I have been told that all files in the same directory comprise a single package, which is a single scope.
答案1
得分: 3
【翻译结果】:
> 编译和运行Go程序
>
> 用法:
>
> go run [编译标志] [-exec xprog] gofiles... [参数...]
>
> Run命令编译并运行由指定的Go源文件组成的主包。Go源文件的定义是以字面上的".go"后缀结尾的文件。
列出所有的gofiles
,
go run main.go otherfile.go
或者,在Linux和其他类Unix系统上,*.go
是匹配目录中所有.go
文件的通配符,
go run *.go
英文:
> 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.
List all the gofiles
,
go run main.go otherfile.go
Or, on Linux and other Unix-like systems, *.go
is the wildcard for all .go
files in the directory,
go run *.go
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论