Golang raises the “stat main.go: no such file or directory” error when trying to run a Go program, but the file “main.go” cannot be found in the specified directory.
To fix the “stat main.go: no such file or directory” error, you can try the following steps:
- You must check the spelling and case of the file name. Go is case-sensitive, so make sure you have the correct spelling and case.
- You need to check the file path: Ensure that the file is located in the correct directory and that the file path is correct.
- Run ls in the terminal to list the contents of the current directory and see if the file is there.
- Use the cd command to navigate to the correct directory, if needed.
- If the file is missing, you can create a new “main.go” file with a basic Go program that includes a main() function.
Golang program that handles the error
package main
import (
"fmt"
"os"
)
func main() {
file := "main.go"
_, err := os.Stat(file)
if os.IsNotExist(err) {
fmt.Println("Error:", file, "does not exist")
return
}
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(file, "exists")
}
Output
Error: main.go does not exist
In this program, we first use the os.Stat() function to check the existence of the file main.go.
If the file does not exist, the os.IsNotExist() function will return true, and we print an error message suggesting that the file does not exist.
If there is any other error, we print the error message.
If there is no error, we print a message indicating that the file exists.
I hope this resolves your error.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.