How do I import definitions from another file in a Go program?

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

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

huangapple
  • 本文由 发表于 2015年3月12日 21:17:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/29010856.html
匿名

发表评论

匿名网友

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

确定