Jump to content

Print debugging statement: Difference between revisions

Added Go
mNo edit summary
(Added Go)
Line 46:
result+1 at line 10
result: 10
</pre>
 
=={{header|Go}}==
Go doesn't have a built-in print debugging statement as such. Nor does it have macros.
 
However, as the following example shows, it is easy enough to mimic a C-like approach by writing a short 'debug' function which can show the value of an expression and its type at the appropriate line number in the program's source code.
 
Note that a label for the expression (whether it's a simple variable or not) must be passed to the 'debug' function as there is no way to deduce it otherwise.
<lang go>package main
 
import (
"fmt"
"runtime"
)
 
type point struct {
x, y float64
}
 
func add(x, y int) int {
result := x + y
debug("x", x)
debug("y", y)
debug("result", result)
debug("result+1", result+1)
return result
}
 
func debug(s string, x interface{}) {
_, _, lineNo, _ := runtime.Caller(1)
fmt.Printf("%q at line %d type '%T'\nvalue: %#v\n\n", s, lineNo, x, x)
}
 
func main() {
add(2, 7)
b := true
debug("b", b)
s := "Hello"
debug("s", s)
p := point{2, 3}
debug("p", p)
q := &p
debug("q", q)
}</lang>
 
{{out}}
<pre>
"x" at line 14 type 'int'
value: 2
 
"y" at line 15 type 'int'
value: 7
 
"result" at line 16 type 'int'
value: 9
 
"result+1" at line 17 type 'int'
value: 10
 
"b" at line 29 type 'bool'
value: true
 
"s" at line 31 type 'string'
value: "Hello"
 
"p" at line 33 type 'main.point'
value: main.point{x:2, y:3}
 
"q" at line 35 type '*main.point'
value: &main.point{x:2, y:3}
</pre>
 
9,490

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.