在另一个文件中的GO对象(同一包中)引发了未定义的错误。

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

GO: Object in another file (same package) throws undefined error

问题

文件:$GOPATH/src/scratch_go_code/main/main.go

package main

import "fmt"

func main() {
    fmt.Println("Hello World")
    cloud := Cloud{}
    cloud.Say()
}

文件:$GOPATH/src/scratch_go_code/main/cloud.go

package main

import "fmt"

type Cloud struct{}

func (Cloud) Say() {
    fmt.Println("I'm a cloud in the main package")
}

运行命令:go install scratch_go_code/... && go run main/main.go
报错信息:

# command-line-arguments
main/main.go:7: undefined: Cloud

有任何想法为什么会出现这个错误?

英文:

File: $GOPATH/src/scratch_go_code/main/main.go

package main

import "fmt"

func main() {
	fmt.Println("Hello World")
	cloud := Cloud{}
	cloud.Say()
}

file $GOPATH/src/scratch_go_code/main/cloud.go

package main

import "fmt"

type Cloud struct{}

func (Cloud) Say() {
	fmt.Println("I'm a cloud in the main package")
}

Running: go install scratch_go_code/... && go run main/main.go
throws:

# command-line-arguments
main/main.go:7: undefined: Cloud

Any idea why?

答案1

得分: 3

你必须使用go build或将两个文件一起传递给go run,例如:

go run main/*.go

使用go build

cd scratch_go_code/ && go build && ./scratch_go_code
英文:

You have to either use go build or pass both files to go run, example :

go run main/*.go

using go build :

cd scratch_go_code/ && go build && ./scratch_go_code 

答案2

得分: 2

这应该可以工作

go build scratch_go_code/main
英文:

This should work

go build scratch_go_code/main

huangapple
  • 本文由 发表于 2014年6月20日 06:15:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/24317094.html
匿名

发表评论

匿名网友

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

确定