How to Die Dump in Go - dd()

Having come from the PHP community, we often have a handy debug function at our disposal dd() (part of Laravel) and var_dump() (native). This may not be perfect (compared with a full on debugging suite) but it is a quick and easy debugging method. This post gives an idea on how you can do the same, but in Go.

We’re helped out by being able to use both variable parameters (shown with ...) and the interface type to handle different types, both strings and integers in our examples.

The only real difference between varDump and dd is that with the die-dump version it also calls os.Exit to stop the program.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
    "fmt"
    "os"
)

func main() {

    varDump("testing", "gophercoding", "debug")
    // = [testing gophercoding debug]

    myVar1 := "gophercoding.com"
    myVar2 := 1234

    dd(myVar1, myVar2)
    // = [gophercoding 1234]

    // END
    // This won't run, as dd() has run to stop program
    fmt.Printf("end of file\n")
}

// varDump will print out any number of variables given to it
// e.g. varDump("test", 1234)
func varDump(myVar ...interface{}) {
    fmt.Printf("%v\n", myVar)
}

// dd will print out variables given to it (like varDump()) but
// will also stop execution from continuing.
func dd(myVar ...interface{}) {
    varDump(myVar...)
    os.Exit(1)
}

dd in golang