This question already has answers here:
Is there a way to get the source code filename and line number in Go?
(1 answer)
Find the path to the executable
(3 answers)
Closed 7 years ago.
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?
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]
}
This should work for you:
package main
import (
"fmt"
"runtime"
)
func main() {
_, fileName, lineNum, _ := runtime.Caller(0)
fmt.Printf("%s: %d\n", fileName, lineNum)
}
Related
This question already has answers here:
Convert time.Time to string
(6 answers)
Closed 2 years ago.
I want to get a timestamp as string. If I use string conversion I got no error but the output is not readable.
Later, I want us it as a part of a filename.
It looks like a question mark for e.g. �
I found some examples like this: https://play.golang.org/p/bq2h3h0YKp
not solves completely me problem. thanks
now := time.Now() // current local time
sec := now.Unix() // number of seconds since January 1, 1970 UTC
fmt.Println(string(sec))
How could I get the timestamp as string?
Something like this works for me
package main
import (
"fmt"
"strconv"
"time"
)
func main() {
now := time.Now()
unix := now.Unix()
fmt.Println(strconv.FormatInt(unix, 10))
}
Here are two examples of how you can convert a unix timestamp to a string.
The first example (s1) uses the strconv package and its function FormatInt. The second example (s2) uses the fmt package (documentation) and its function Sprintf.
Personally, I like the Sprintf option more from an aesthetic point of view. I did not check the performance yet.
package main
import "fmt"
import "time"
import "strconv"
func main() {
t := time.Now().Unix() // t is of type int64
// use strconv and FormatInt with base 10 to convert the int64 to string
s1 := strconv.FormatInt(t, 10)
fmt.Println(s1)
// Use Sprintf to create a string with format:
s2 := fmt.Sprintf("%d", t)
fmt.Println(s2)
}
Golang Playground: https://play.golang.org/p/jk_xHYK_5Vu
This question already has answers here:
How to access command-line arguments passed to a Go program?
(6 answers)
Closed 2 years ago.
I would like to log all the flags(cmdline args) passed to a program at startup. How do I do this? Currently the program uses flag package to read the flags into the program .
If you're using the flag package, there is the concept of a "flag" which is a defined command line argument i.e.
name := flag.String("name", "default", "some name")
And also the concept of an "arg" which is an undefined command line argument (i.e. not a flag).
You can get the list of args with flag.Args() which returns string[].
There doesn't seem to be a way to get the list of flags. There are Visit functions. You could use VisitAll that takes a function to execute on each flag:
flag.VisitAll(func(f *flag.Flag) {
fmt.Printf("%s: %s\n", f.Name, f.Value)
})
You can use os.Args, which is a slice of strings, from the os package.
E.g:
package main
import (
"log"
"os"
)
func main() {
log.Println(os.Args)
}
This question already has answers here:
Multiple values in single-value context
(6 answers)
Closed 4 years ago.
Go newbie here.
I am trying to run very simple example on go1.11.4 windows/amd64
Here is my code below;
sandbox: https://play.golang.org/p/GoALi4HYx3L
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Print("Enter a grade: ")
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter text: ")
input := reader.ReadString('\n')
fmt.Println(input)
}
And I am getting following error:
prog.go:13:28: multiple-value
reader.ReadString() in single-value context
Am I missing something here?
Check the documentation for ReadString, especially the part that describes return values (Tip: it is in the title of the section).
https://golang.org/pkg/bufio/#Reader.ReadString
Also, it worse check this reading also
https://gobyexample.com/multiple-return-values
This question already has an answer here:
Passing interface{} or []interface{} in Golang
(1 answer)
Closed 4 years ago.
I'm trying to create a function that prints out the len of a list passed into it, regardless of the type of the list. My naive way of doing this was:
func printLength(lis []interface{}) {
fmt.Printf("Length: %d", len(lis))
}
However, when trying to use it via
func main() {
strs := []string{"Hello,", "World!"}
printLength(strs)
}
It complains saying
cannot use strs (type []string) as type []interface {} in argument to printLength
But, a string can be used as a interface{}, so why can't a []string be used as a []interface{}?
You can use reflect package - playground
import (
"fmt"
"reflect"
)
func printLength(lis interface{}) {
fmt.Printf("Length: %d", reflect.ValueOf(lis).Len())
}
This question already has answers here:
How can I read from standard input in the console?
(12 answers)
Closed 7 years ago.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
fmt.Println("insert y value here: ")
input := bufio.NewScanner(os.Stdin)
fmt.Println(input.Text)
}
How do I make the program wait, until the user inputs data?
Scanner isn't really ideal for reading command line input (see the answer HectorJ referenced above), but if you want to make it work, it's a call to Scan() that you're missing (also note that Text() is a method call):
func main() {
fmt.Print("insert y value here: ")
input := bufio.NewScanner(os.Stdin)
input.Scan()
fmt.Println(input.Text())
}