Why can't the go run command find the second file in the main package?

I have a problem when go run main.go raises an error:

 # command-line-arguments ./main.go:9: undefined: test 

However, the go build && ./goruntest compiling and running the program is just fine.

Output:

Hello from test ()

Hello from sameFileTest ()

Hello from pkgtest.Test ()

Hello from pkgtest.Test1 ()

I have a directory setup like this:

 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 the package main , and I also understand that there is no real reason to have the second file in main .

My question is: Why go run cannot handle this setup, but creating and running executable files is just fine?

EDIT

Included second file in pkgtest

I also understand that the go run main.go gotest1.go works, but why do I need to specify gotest1.go ?

I initially omitted these details for the sake of brevity. But now I see that they are important for the question.

+6
source share
1 answer

Try to provide all the relevant go run files

 $ 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. 
+6
source

Source: https://habr.com/ru/post/978169/


All Articles