I'm writing a Lisp variant in Go and want to define constants for Nil
and EmptyList
. These will be referenced throughout the codebase, but I want to prevent them from being accidentally re-defined.
// Representation of the empty list
var EmptyList = (*List)(nil)
I can't use a const
here for two reasons:
const
definitions cannot be nil
const
definitions cannot be pointersWhat options do I have to ensure EmptyList
is always the nil pointer?
In Go, use a function. For example,
package main
import "fmt"
type List struct{}
func IsEmptyList(list *List) bool {
// Representation of the empty list
return list == (*List)(nil)
}
func main() {
fmt.Println(IsEmptyList((*List)(nil)))
}
Output:
true
The function will be inlined.
$ go tool compile -m emptylist.go
emptylist.go:7: can inline IsEmptyList
emptylist.go:13: inlining call to IsEmptyList
emptylist.go:7: IsEmptyList list does not escape
emptylist.go:13: IsEmptyList((*List)(nil)) escapes to heap
emptylist.go:13: main ... argument does not escape
$