To delete/remove a file in Go, use the built-in os.Remove()
function:
package main
import (
"log"
"os"
)
func main() {
if err := os.Remove("testfile.txt"); err != nil {
log.Fatal(err)
}
}
If the file exists, the function removes the file without any error. If there is some problem, it returns an error of type *os.PathError
. For example, if the file does not exist, the error is:
2022/04/05 06:16:05 remove testfile.txt: no such file or directory
exit status 1