Skip to content

How to resolve 'go run: cannot run non-main package' when running golang program

Problem

When running a Go program as follows:

Terminal window
go run main.go

Sometimes, you may encounter this error:

Terminal window
go run: cannot run non-main package

Why does this error occur? The Go program is correct, I promise!

Environment

  • Go version: go1.14

The Code

The main code of the program is:

main.go
package gin
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Reason

The error occurs because the package declaration in the Go source file is incorrect. Executable commands in Go must always use the main package. The first statement in a Go source file must be package main.

Solution

To resolve this issue, change the package declaration to main:

main.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}

Run the program again, and the error will no longer appear. It works!

By the Way

Go programs are organized into packages. A package is a collection of source files in the same directory that are compiled together. Functions, types, variables, and constants defined in one source file are visible to all other source files within the same package.

Summary

In this post, we explored how to resolve the “go run: cannot run non-main package” error in Go. The key takeaway is that executable programs in Go must use the main package. By ensuring the correct package declaration and understanding the role of the main package, you can avoid this common issue. Remember to always declare package main for executable programs and use other package names for libraries or reusable components.

Final Words + More Resources

My intention with this article was to help others who might be considering solving such a problem. So I hope that’s been the case here. If you still have any questions, don’t hesitate to ask me by email: Email me

Here are also the most important links from this article along with some further resources that will help you in this scope:

Oh, and if you found these resources useful, don’t forget to support me by starring the repo on GitHub!