创建可执行文件后获取当前文件名

Get current file name after creating executable

我可以获得当前目录和当前 .go 文件的名称,但是如果我使用 go build 从文件构建 .exe,那么我仍然会得到 .go 名字.

.../Project/Test/testfile.go

go build 构建 testfile.go 后,我有这些:

1) .../Project/Test/testfile.go

2) .../Project/Test/main.exe

当我执行 main.exe 时,我得到 testfile 但是我想在执行 main.exe

后得到 main 名称
package main

import (
    "errors"
    "fmt"
    "path/filepath"
    "runtime"
    "strings"
)

func GetFileName() string {
    _, fpath, _, ok := runtime.Caller(0)
    if !ok {
        err := errors.New("failed to get filename")
        panic(err)
    }
    filename := filepath.Base(fpath)
    filename = strings.Replace(filename, ".go", "", 1)
    return filename
}

func main() {
    fmt.Print(GetFileName())
}

os package provides os.Args[0] to obtain the executable name, or if you want the whole path you could use os.Executable, as @Peter有建议