others-how to solve golang error: Main file has non-main package or doesn't contain main function

Problem

When we run a golang file in goland or other go IDE, sometimes, we get this error:

Main file has non-main package or doesn't contain main function

image-20201214213809352

But our code does have the main function:

package hello1

import "fmt"

func main() {
	fmt.Printf("hello world")
}

As you can see ,there is a main function in our code, why did this happen?

Environment

  • MacOS 10.14
  • Golang go version go1.14 darwin/amd64

Reason

Golang would try to find the main package to run your code, but in our example, there is no package other than the package ‘hello1’, so the run would fail.

Solution

The key point is to tell golang there is a main package in our code, so let’s do it:

package main

import "fmt"

func main() {
	fmt.Printf("hello world")
}

As you can see, we change from package hello1 to package main, run the code again:

GOROOT=/usr/local/go #gosetup
GOPATH=/Users/bswen/GoProjects #gosetup
/usr/local/go/bin/go build -o /private/var/folders/l1/bxn8rt2j6hzg6zc6gjxy_3rr0000gn/T/___go_build_main_go /Users/bswen/GoProjects/src/awesomeProject/hello1/main.go #gosetup
/private/var/folders/l1/bxn8rt2j6hzg6zc6gjxy_3rr0000gn/T/___go_build_main_go
hello world
Process finished with exit code 0

One more thing

According to this article:

In Go, source files are organized into system directories called packages, which enable code reusability across the Go applications.Within a single folder, the package name will be same for the all source files which belong to that directory.

About package main

when you develop executable programs, you will use the package “main” for making the package as an executable program. The package “main” tells the Go compiler that the package should compile as an executable program instead of a shared library. The main function in the package “main” will be the entry point of our executable program. When you build shared libraries, you will not have any main package and main function in the package