0

I was researching on topic to analyze the codes that are executed with different inputs in Go. Assuming I have following code:

1  package main
2  import "fmt"
3  func main() {
4      var i int
5      _, err := fmt.Scanf("%d", &i)
6      if i%2 == 0 {
7         fmt.Println("input is even")
8      } else {
9         fmt.Println("input is odd")
10     }
11  }

The codes that are executed are based on the value of input. If your input is an even number, like 20, then the output should be [1, 2, 3, 4, 5, 6, 7, 11]. Otherwise, if the value of input is odd, like 21, then output will be [1, 2, 3, 4, 5, 6, 8, 9, 10, 11].

I am looking for a way in Go to print out the line numbers executed in runtime. If there are other imported go files, the line numbers that are executed in those files should be also printed out.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Steve C.
  • 1
  • 1
  • 1
    Maybe I understand... you're not talking about that code, per se... you want to know which of those lines of code are executed. What you need is the [coverage tool](https://stackoverflow.com/questions/10516662/how-to-measure-code-coverage-in-golang). – Jonathan Hall Sep 21 '19 at 16:14
  • @Flimzy Thank you for the advice. I think I got it. What I need to do is integrate the coverage tool into my code and make sure there's coverage report generated in each execution. Then I can have the line numbers in each execution. Thank you so much. – Steve C. Sep 21 '19 at 16:30
  • 1
    It's not intended for running in normal execution. It's a profiling tool, meant to run on occasion (during testing). But maybe you can force it to do what you want. – Jonathan Hall Sep 21 '19 at 16:31
  • Another way of looking at what a program is doing is its callgraph. Have a look at https://github.com/protolambda/gocyto and https://github.com/TrueFurby/go-callvis – marco.m Sep 21 '19 at 20:47
  • @Flimzy I tried "testing" package to collect lines of code that are tested with "go test" command and it works. Thanks for the advice. This should a candidate solution. I will continue to look for another easier way to collect these information during the runtime execution without using "go test" – Steve C. Sep 21 '19 at 20:57
  • @marco.m Thank you for the advice. I will check them out to see if I can obtain some ideas from their source codes. – Steve C. Sep 21 '19 at 20:57

0 Answers0