I'm well aware of the fact that Go does not have assertions and fully agree with
"Why Does Go Not Have Assertions?" I agree that programmers may use assertions as crutches in production code.
So what, then, is a nice way to write expository code that is used to explain the language to a reader? For example, in Lua, if wanted to explain scope to someone, I could give them the executable code:
-- Lua
x = 1
do
assert(x == 1) -- global x because local not yet seen
local x = x + 2 -- uses global x on right hand side
assert(x == 3) -- now, FINALLY, we see the local x
end
assert(x == 1) -- back in the global scope, local gone
and in Python I can explain types to people with executable code like
# Python
assert type(5) == int
assert type(True) == bool
assert type(5.7) == float
assert type(9 + 5j) == complex
and even in Ruby, we don't have asserts, but we can simulate them with `fail unless`:
# Ruby
fail unless 5.send(:abs) == 5
fail unless 5.send('abs') == 5
fail unless 5.abs == 5
In Clojure I have to import something from core, but it's pretty lightweight once I add a use line:
; Clojure
(use 'clojure.test)
(is (= (type 3) Long))
(is (= (type 5.0) Double))
(is (= (type 4/7) clojure.lang.Ratio))
(is (= (type 5N) clojure.lang.BigInt))
Each of these things allow one to illustrate features of the language without using comments (which there's no reason to believe) and print statements (which require looking at), and that's super nice, IMHO.
What can I write in Go? Is it correct to use panics? Or log.Fatal? I would really like to know the idiomatic equivalent of the above in Go. Here is what I have tried:
// Go
package main
import "math"
func twice(f func(float64)float64, x float64) float64 {
return f(f(x))
}
func square(x float64) float64 {
return x * x
}
func main() {
addTwo := func(x float64)float64 {return x + 2}
if twice(square, 4) != 256 {panic("")}
if twice(addTwo, 100) != 104 {panic("")}
if twice(math.Log2, 256) != 3 {panic("")}
}
I'm not sure about if....panic.
What should I do? What is the most idiomatic way to do this in Go?
Yes I do know how to use the testing package. Is that the best way?