5

Say I have a file:

i_want_this_name.go:

package main

func main(){
    filename := some_func() // should be "i_want_this_name"
}

How do I get the executing code's file's name in go?

Derek
  • 11,980
  • 26
  • 103
  • 162

2 Answers2

2

The name of the command can be found in os.Args[0] as states in the documentation for the os package:

var Args []string

Args hold the command-line arguments, starting with the program name.

To use it, do the following:

package main

import "os"

func main(){
    filename := os.Args[0]
}
martinhans
  • 1,133
  • 8
  • 18
2

This should work for you:

package main

import (
  "fmt"
  "runtime"
)

func main() {
  _, fileName, lineNum, _ := runtime.Caller(0)
  fmt.Printf("%s: %d\n", fileName, lineNum)
}
plusmid
  • 211
  • 1
  • 3