I am experiencing an issue where go run main.go
produces the error:
# command-line-arguments
./main.go:9: undefined: test
However the commands go build && ./goruntest
compile and run the program just fine.
The output is:
Hi from test()
Hi from sameFileTest()
Hi from pkgtest.Test()
Hi from pkgtest.Test1()
I have the directory set-up like so:
go/src/github.com/username/goruntest/
pkgtest/
pkgtest.go
pkgtest1.go
main.go
test2.go
Here is the code.
main.go
package main
import (
"fmt"
"github.com/username/goruntest/pkgtest"
)
func main() {
fmt.Println(test()) // main.go:9
fmt.Println(sameFileTest())
fmt.Println(pkgtest.Test())
fmt.Println(pkgtest.Test1())
}
func sameFileTest() string {
return "Hi from sameFileTest()"
}
gotest1.go
package main
func test() string {
return "Hi from test()"
}
pkgtest/pkgtest.go
package pkgtest
func Test() string {
return "Hi from pkgtest.Test()"
}
pkgtest/pkgtest1.go
package pkgtest
func Test1() string {
return "Hi from pkgtest.Test1()"
}
I understand that the problem is the second file as part of package main
and I also understand that there is no real reason to have a second file in main
.
My question is: Why is go run
unable to handle this set-up but building and running the executable works just fine?
EDIT
Included a second file in pkgtest
I also understand that the command go run main.go gotest1.go
works but why do I need to specify gotest1.go
?
I originally omitted these details for the sake of brevity. But now I see they are important to the question.
Try providing all relevant files to go run
$ go help run
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With