英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论