Delve - break when value of a variable changes

(1) Is there a way to stop the execution of a program when a variable changes its value?

Of course, I know we can set a breakpoint at some lines, but I would want just to set a variable, and when it changes, stop the program for debugging.

(2) I also want to see execution flow of a program (by logging to a file / printing on screen). Is there any way I can run my program and see the same (without stepping through each line)?

Please consider below example (https://play.golang.org/p/vOvW4GAM0j)

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {

    rand.Seed(time.Now().Unix())
    r := rand.Intn(100)
    var i int

    if r%2 == 0 {
        i = 2
    } else {
        i = 1
    }

    fmt.Println(i)
}

Now I want to break when value of i changes to non-zero value. It may be from line 16 or line 18.

(1) Is there any way I can set (conditional) breakpoint so that it breaks when value of i changes OR I have to put breakpoint on both lines (16 and 18)?

(2) Also, I want to know how program was executed… like line13 then line15 then line17, line18… (assuming odd random number)

Thanks!

I cannot comment in detail on delve (AFAIK it has conditional breakpoints but no “break on variable change” feature, and it seems to allow setting tracepoints on line level), but in general, if your goal is to inspect single functions in order to learn what happens, you might not need a debugger.

I often use go-spew for quickly inspecting local parts of a code. It is as simple as placing a spew.Dump(<variable>) in order to pretty-print a data structure (even a nested one), and when I am done, the spew calls are easy to remove because the string “spew” is rarely used in typical code :wink:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.