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.
Go 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 seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.