To check if a file exists in Golang, you can use the os.Stat() function to get the file information. If the file does not exist, the os.Stat() function will return an error.

Here is an example of how to check if a file exists in Golang:

Go: check if a file exists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import (
    "fmt"
    "os"
)

func main() {
    filename := "myfile.txt"
    _, err := os.Stat(filename)
    if os.IsNotExist(err) {
        fmt.Printf("The file %s does not exist\n", filename)
    } else {
        fmt.Printf("The file %s exists\n", filename)
    }
}

In the code above, we use the os.Stat() function to get the file information for the file "myfile.txt". If the file does not exist, the os.Stat() function will return an error. We use the os.IsNotExist() function to check if the error is a "file not found" error, and if so, we print a message saying that the file does not exist. Otherwise, we print a message saying that the file exists.