You can't have the same symbol declared twice at the package level in the same package.
And if you have 2 files in the same folder, both having package main
declaration, that is exactly what you're doing. This is why your IDE complains: it tries to build / compile those 2 files as one package, same as writing go build .
: this designates the package in the current folder, including all source files.
go run main.go
and go run second.go
works because you specify files to build (more specifically a single file), not packages. And having a single main.go
or second.go
being the main
package does not violate the above rule: each file only contains the main()
function once.
So in short: go run main.go
ignores second.go
.
Usually if you want to create multiple apps with multiple main()
functions in the same project, it's easiest to just place different main()
functions in different folders, conventionally inside a cmd
folder.
See Command Go:
Usage:
go build [-o output] [-i] [build flags] [packages]
Build compiles the packages named by the import paths, along with their dependencies, but it does not install the results.
If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package.
Usage:
go run [build flags] [-exec xprog] package [arguments...]
Run compiles and runs the named main Go package. Typically the package is specified as a list of .go source files, but it may also be an import path, file system path, or pattern matching a single known package, as in 'go run .' or 'go run my/cmd'.
Also see What does go build build?