How to Fix stat main.go: no such file or directory

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:

  1. 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.
  2. You need to check the file path: Ensure that the file is located in the correct directory and that the file path is correct.
  3. Run ls in the terminal to list the contents of the current directory and see if the file is there.
  4. Use the cd command to navigate to the correct directory, if needed.
  5. 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.