Reputation: 6519
Considering the sample hello world with the wrong package name with the file named as main.go
package test
import "fmt"
func main() {
fmt.Println("hello world")
}
on go build main.go
the build doesn't work (doesn't generate the executable) because of the incorrect package name. But why no error is thrown?
Upvotes: 0
Views: 511
Reputation: 417412
A package name test
is not incorrect, it is valid according to Spec: Package clause:
PackageClause = "package" PackageName .
PackageName = identifier .
test
is a valid Go identifier.
As to what does go build main.go
do?
Generally you list packages to go build
, but you may also list .go
source files, just as in your example.
Quoting from go help build
:
If the arguments to build are a list of .go files, build treats them as a list of source files specifying a single package.
So go build
simply built your test
package, consisting of a single main.go
source file. It is not an error to add a main()
function to a package that is not main
.
As to why "nothing" happens: go build
generates no output if everything is ok, and it outputs error if something is not right. go build
applied on a non-main
package just "checks" if the package can be built, but it discards the result. Please check What does go build build?
Upvotes: 3