0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Krishnadas PC
  • 5,981
  • 2
  • 53
  • 54

1 Answers1

3

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?

icza
  • 389,944
  • 63
  • 907
  • 827
  • I meant it failed to generate the build file. Not a syntax error in the code. I will go through the link. – Krishnadas PC Nov 28 '18 at 14:08
  • 2
    @KrishnadasPC `go build` shouldn't generate anything for non-main packages. So it works as expected. – icza Nov 28 '18 at 14:11